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:
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;
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:
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)
.
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;
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;
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);
The following code resume the operations explained on this page: