Adding Elements: push_back()

A vector doesn't have to keep the same number of elements. The method push_back() adds an element to the end of a vector. You write the new element in the parentheses:

std::vector<std::string> carBrands = {"Mercedes", "Cadillac"};
carBrands.push_back("Volvo");
std::cout << carBrands[2] << std::endl;
std::cout << carBrands.size() << std::endl;

This prints:

Volvo
3

Read carBrands.push_back("Volvo") from left to right: for the vector carBrands, call the method push_back(), which adds "Volvo" to its end. The vector changes, and so does its size. The new element must have the type of the vector's elements: you add texts to a vector of texts and numbers to a vector of numbers.

This way, you can also build a vector step by step, starting from an empty vector:

std::vector<int> points;
points.push_back(12);
points.push_back(7);
std::cout << "Count: " << points.size() << std::endl;
std::cout << "Last: " << points[points.size() - 1] << std::endl;

This prints:

Count: 2
Last: 7

Watch out: assigning to an index past the end doesn't add a new element. If you wrote points[2] = 30; in this example, the vector would still have two elements, and the value 30 would be written somewhere into the memory after its end. The program could then behave unpredictably or crash. With points.at(2) = 30;, the program would at least stop with an error. Always add new elements with push_back().

Instructions

Ava has joined the team. Add "Ava" to the end of colleagues with the method push_back().

Print the number of colleagues and the last one of them, one below the other, so that the output includes the lines Colleagues: 4 and Last: Ava. Find the last colleague with size() - 1.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

6/10

Next