C++ std::vector

The C++ std::vector is a container for storing dynamic size array. std::vector is not a class for dealing with mathematical vectors. An std::vector is an array.

The advantages of std::vector are:

Declaration

To use the std::vector containers, you have to include the following header file:

#include <vector>

Since std::vector is a container, you have to specify the type of the element when calling the constructor. In the following example, we create an empty vector (or an empty array) of integer:

std::vector<int> myVector;

You can create vectors of any types:

std::vector<char> myVectorOfCharacters;
std::vector<float> myVectorOfFloats;
std::vector<myCLass> myVectorOfObjects;

Append new element

To add a new element to the end, use the .push_back() member function:

myVector.push_back(12);

After this line, the vector size has increased of 1, and the last cell contains 12. On the following example, we append 3 values in the vector :

std::vector<int> myVector;
myVector.push_back(17);
myVector.push_back(25);
myVector.push_back(12);

The vector contains the following values:

The vector after appending three values

Get element

There are two ways to access elements. The first one is to use the syntax of classical arrays with brackets:

myVector[2];

The second option is to use the .at() member function:

myVector.at(2);

The second option is convinient to access elements from pointers: pointer->at(5).

Update elements

The access also works for writing values in the cells:

myVector[0] = 15;

The above code provides the same result as:

myVector.at(0) = 15;

Get vector size

The .size() member function returns the size of the vector (number of cells)

std::vector<int> myVector;
myVector.push_back(17);
myVector.push_back(25);
myVector.push_back(12);

// Display 3
std::cout << myVector.size() << endl;

Remove element

The .erase() member function is used to remove an element from the array. Note that the function expect an iterator as parameters. You can't write:

myVector.erase(0);

To remove the first element, you have to write:

myVector.erase(myvector.begin());

To erase the third element, use :

myVector.erase(myvector.begin()+2);

Full example

The following code resume the operations explained on this page:

See also


Last update : 10/21/2022