Adding Elements to Vector
Now we'll start looking at methods that make working with vectors easier.
We'll start with the push_back()
method, which inserts an element at the end of the vector.
We'll show how it's used with an example and then explain the notation:
std::vector carBrands = {"Mercedes", "Skoda"};
carBrands.push_back("Volvo");
// Vector content {"Mercedes","Skoda","Volvo"}
The push_back()
method uses dot notation. Before the dot, we have the vector to whose end we want to add a new element. After the dot follows the push_back()
method, which inserts the value in parentheses at the end of the vector. In the parentheses is the value "Volvo"
, which we insert at the end of the vector.
It sounds complicated, but as you can see, the code is relatively simple.
Instructions
Add a new colleague "Eva"
to the vector colleagues
using the push_back()
method.
Print the fourth colleague.
Start programming for free
7/10