To use vectors in your code, you need the appropriate library -
Vectors are declared with the following syntax:
The number of elements is optional. You could declare it like this:
And that would declare an empty vector — a vector that contains zero elements.
// 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:
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). 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 functionThis function removes the last element from the vector.Unfortunately
pop_back()doesn't return the value of the popped element.
C++ strings behave (to some extent) like vectors of charstring s = "eyrie";
s = s; // s is now "eerie"
string t = "cat";
char ch = t; // ch is the letter 'c'; note that ch is of type char, not type string
t = t;
t = 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).