In C++‘s STL, vectors are dynamic arrays that can change in size. It can only store values of the same data type (i.e., a vector declared with int
can only store integers).
Vectors are implemented with ordinary arrays that are re-allocated if they’re at full capacity. Memory is allocated for a new vector with a greater capacity than is needed (usually ) and memory is freed. For larger , this can get expensive, so we should specify its size at definition wherever possible.
Just like arrays, it has access time and search time and suffers from the same problems with element deletion.
Constructor
To initialise a 1D vector with an initial size (and optionally a default value), we can use the following code:
The compiler will often take a well-reasoned default value.
To initialise a 2D vector with an initial size, we extend the same syntax as above:
Methods
Structure manipulations:
push_back()
: adds an element to the rear of the list. On average, this has a time complexity of .clear()
: wipes the contents of the vector.resize(n)
: resize the vector to store elements.
Element access:
begin()
andend()
: returns iterator of the beginning or end indices of the vector. It also supportsrbegin()
andrend()
.at()
: memory-safe way to access vector elements. It throws an error if the element is out of bounds.
Other useful methods include:
size()
, which gives us the size of the vector.empty()
is a Boolean.