If you look up documentation for vector on a site like cppreference.com, you will find the functions void vector<T>::push_back(T value) and void vector<T>::pop_back(). The syntax vector<T> is used to indicate βa vector of the type Tβ where T could be anything - string, int, etc... So vector<T>::push_back says something like βthe push_back function for a vector of any type βTββ.
These functions can be used to add or remove elements from the end of a vector. push_back(T value) takes a value of the type the vector can contain (type T) and adds it to the end of the vector. pop_back() simply removes the last element.
vector<string> words = {"Hello"};
words.push_back("there"); // now {"Hello", "there"}
words.push_back("world"); // now {"Hello", "there", "world"}
The end of a vector is the βnormalβ location to add or remove elements due to the way the data is stored. All of the elements of a vector are stored in one contiguous block of memory. We are not allowed to have gaps in the middle. The way that the compiler figures out where a given element is in memory is by doing a calculation that looks like:
For example, if the data starts at memory address \(1000\) and each element takes up 4 bytes, the address of the element at index 3 would be calculated as:
That math assumes that there are no gaps in the data. If there were, we could not just multiply the index by the size of each element to find the address.
Similarly, to insert something in the middle, we would first need to move all of the elements after that point over to make room for the new element before we insert it.
This is much slower, especially in a long vector. So to encourage us to add and remove elements at the end, there is only pop_back() and push_back and not a pop_front() or pop_middle().