To use vectors in your code, you need the appropriate library -
#include Vectors are declared with the following syntax:
vector
The number of elements is optional. You could declare it like this:
vector
And that would declare an empty vector — a vector that contains zero elements.
Examples:
vector
vector
vector
// initially empty (contains 0 strings)
After a vector has been declared specifying a certain number of elements, we can refer to individual elements in the vector using square brackets to provide a subscript or index, as shown below:
grades[5]
v.size()
Returns the number of elements in v.
The = operator
You can use the = (assignment) operator to assign one vector to another, for example v1 = v2
, so long as they are vectors of the same type (eg both vector
or vector
). In this case the contents of v1 are overwritten with the contents of v2 and v1 is truncated or extended to be the same length as v2.
The push_back() member function
This function allows you to add elements to the end of a vector.
The pop_back() member function
This function removes the last element from the vector.Unfortunatelypop_back()
doesn't return the value of the popped element.
C++ strings behave (to some extent) like vectors of char
string s = "eyrie";s[1] = s[0]; // s is now "eerie"
string t = "cat";
char ch = t[0]; // ch is the letter 'c'; note that ch is of type char, not type string
t[0] = t[1];
t[1] = ch; // t is now "act"
Vectors are good at:
- Accessing individual elements by their position index (constant time).
- Iterating over the elements in any order (linear time).
- Add and remove elements from its end (constant time).