C++ Vectors – std::vector – Containers Library

Vectors are sequence containers (same as dynamic arrays) which resizes itself automatically. The size changes (i.e. vector can shrink or expand as needed at run time) when an element is inserted or deleted, with their storage being handled automatically by the container.

Just like arrays, vector elements are placed in adjacent memory locations so that they can be accessed and traversed using iterators i.e. subscript operator []. Vector elements can also be accessed by using offsets to regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array.

In vectors, data is inserted at the end and inserting data at the end may require extending the array. To support shrink and expand functionality at run-time, vector container may allocate some extra storage to accommodate for possible growth thus container have actual capacity greater than the size.

Therefore, compared to the other dynamic sequence containers (deques, lists and forward_lists), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. However, vector consumes more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.

Defining a Vector in C++

Below is the C++ definition of std::vector from <vector> header library file

1 template < class T , class Allocator = std :: allocator < T > > class vector ;

Vector Parameters

T – The type of elements. T may be substituted by any other data type including user-defined type.

Allocator − Type of allocator object.By default, the allocator class template is used, which defines the memory allocation/de-allocation model, construct/destroy elements and is value-independent.

Vector Functions

Vectors library provides lots of functions to traverse, access and manipulate vectors. There are a lot many helper/utility vector functions to determine the capacity and size of vectors.

Traversing Vectors – Iterators

As vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. There are four basic functions associated with vectors which are used to traverse vectors i.e.

begin() – Returns an iterator pointing to the first element in the vector end() – Returns an iterator pointing to the theoretical element that follows last element in the vector rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)

C++ Program to demonstrate Vector Iterators

Consider the following program which demonstrate the use of iterators to access and traverse vector elements using the iterator member types discussed above.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include <iostream> #include <vector> using namespace std ; int main ( ) { vector < int > scores ; vector < int > :: iterator i ; vector < int > :: reverse_iterator ri ; for ( int i = 1 ; i <= 5 ; i ++ ) { scores . push_back ( i ) ; } cout << "Output of begin() and end():" ; for ( i = scores . begin ( ) ; i != scores . end ( ) ; ++ i ) { cout << ' ' << * i ; } cout << endl << endl ; cout << "Output of rbegin() and rend():" ; for ( ri = scores . rbegin ( ) ; ri != scores . rend ( ) ; ++ ri ) { cout << ' ' << * ri ; } return 0 ; }

Output:

1 2 3 Output of begin() and end(): 1 2 3 4 5 Output of rbegin() and rend(): 5 4 3 2 1

Accessing Vector Elements – Access Functions

Vector elements can be accessed using the following vector functions. Any/combination or all of these functions can be used to access vector elements in different situations.

front() Returns a reference to the first element in the container. back() Returns reference to the last element in the container. at() Returns a reference to the element at specific position in the vector by using a reference operator (as mentioned below) Reference Operator [r] Returns a reference to the element at position ‘r’ in the vector

C++ Program to Access Vector Elements

Consider the following program which demonstrate the access and traverse vector elements using the access functions as discussed above.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <iostream> #include <vector> using namespace std ; int main ( ) { vector < int > ints = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; cout << "Using at() function - Value returned by ints.at(4) = " << ints . at ( 4 ) ; cout << endl ; cout << "Using front() function - Value returned by ints.front() = " << ints . front ( ) ; cout << endl ; cout << "Using back() function - Value returned by ints.back() = " << ints . back ( ) ; cout << endl ; cout << "Reference Operator [r] : Value at position ints[2] = " << ints [ 2 ] ; cout << endl ; return 0 ; }

Output:

1 2 3 4 5 6 7 Using at() function - Value returned by ints.at(4) = 5 Using front() function - Value returned by ints.front() = 1 Using back() function - Value returned by ints.back() = 10 Reference Operator [r] : Value at position ints[2] = 3

Manipulate Vector Elements – Modifier Functions

The following C++ functions are used to interact with vector elements and manipulate them.

insert() – Inserts elements into the vector. assign() – Assigns new content to vector and resize emplace() – Constructs element in-place push_back() – Adds an element to the end of the vector and increment the size emplace_back() – Constructs an element in-place at the end pop_back() – Removes the last element of the vector and decrements the size resize() – Changes the number of elements stored swap() – Swaps the contents of two vectors clear() – Clears the contents of the vector erase() – Removes the specific element or range of elements from vector

C++ Program to Manipulate Vector Elements

Consider the following program which demonstrate the manipulation of vector elements using the modified functions as discussed above.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <iostream> #include <vector> using namespace std ; void print_vec ( const vector < int > & vec ) { for ( auto x : vec ) { cout << ' ' << x ; } cout << '

' ; } int main ( ) { cout << "Initial Vector:" << endl ; vector < int > vec ( 3 , 100 ) ; print_vec ( vec ) ; cout << "Insert Value: 200 at the beginning of Vector:" << endl ; auto it = vec . begin ( ) ; it = vec . insert ( it , 200 ) ; print_vec ( vec ) ; cout << "Insert Value: 300 twice at the end of Vector:" << endl ; it = vec . end ( ) ; vec . insert ( it , 2 , 300 ) ; print_vec ( vec ) ; }

Output:

1 2 3 4 5 6 7 8 9 10 11 Initial Vector: 100 100 100 Insert Value: 200 at the beginning of Vector: 200 100 100 100 Insert Value: 300 twice at the end of Vector: 200 100 100 100 300 300

Capacity and Size Functions

empty() – This function checks whether the container is empty or not. size() – Returns the number of elements in the vector max_size() – Returns the maximum possible number of elements of vector reserve() – Reserves storage i.e. increase the capacity of the vector to a value that’s greater or equal to new_cap. capacity() – Returns the number of elements that can be held in currently allocated storage shrink_to_fit() – Reduces memory usage by freeing unused memory

C++ Program to display number of elements in Vector

The following C++ program displays the number of elements in vector using size() function.

1 2 3 4 5 6 7 8 9 10 11 #include <vector> #include <iostream> using namespace std ; int main ( ) { vector < int > ids { 1 , 3 , 5 , 7 } ; cout << "ids contains " << ids . size ( ) << " elements.

" ; }

Output:

1 ids contains 4 elements.

Zero Sized Vectors

Zero sized vectors are also possible and valid. In that case vector.begin() and vector.end() points to same location. But behavior of calling front() or back() is undefined.