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:<br><b> #include< vector ></b>

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

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:<br><b> cout << v2.capacity() - v2.size() <<endl;</b>

Add two more elements to the end of v2:<br><b> v2.push_back(13);<br> v2.push_back(23);</b>

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

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

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

Items you will need

More Articles