How to Use a C++ Vector to Store Data

by Contributor

The vector is the official array of C++. Part of the Standard Template Library, it's a template container class that stores same-typed data in an uninterrupted region of memory. As a C++ class, it offers many useful features, such as resizing, that reduce code size and save time. Its indexing operations are as efficient as those of the dumb arrays in C.

Include the vector header file so that your program can access the C++ class and its functions:
#include< vector >

Create an empty vector of type int. Then create a vector with 10 copies of 7:
vector< int > v; // empty
vector< int > v2(10, 7);

Use v2 to find the difference between how much memory has been allocated for v2 compared to its size. The memory allocated is always greater than or equal to the size:
cout << v2.capacity() - v2.size() <

Add two more elements to the end of v2:
v2.push_back(13);
v2.push_back(23);

Double the size of v2 and give the additional elements a value of 64:
v2.resize(v2.size()*2, 64);

Iterate across the vector using a special-purpose pointer called an iterator. Output the elements to the console as follows:
for( vector::iterator it = v2.begin(); it != v2.end(); it++ ){
cout << *it << " ";
}

Erase elements 2 and 3 from the vector. Then erase all the elements at once:
v2.erase(v2.begin()+1, v2.begin()+3); // erases elements 2 and 3
v2.clear(); // erases all the elements

Items you will need