Removing Elements: pop_back()

The opposite of push_back() is the method pop_back(): it removes the last element of a vector. You don't write anything in the parentheses, but you do have to write the parentheses.

std::vector<std::string> colors = {"blue", "green", "pink"};
colors.pop_back();
std::cout << colors.size() << std::endl;
std::cout << colors[colors.size() - 1] << std::endl;

This prints:

2
green

The element "pink" is gone, and the last element is now "green".

The method pop_back() only removes the element, it doesn't give you anything. If you need the removed element, read it before you remove it:

std::vector<std::string> colors = {"blue", "green", "pink"};
std::string lastColor = colors[colors.size() - 1];
colors.pop_back();
std::cout << "Removed: " << lastColor << std::endl;
std::cout << "Left: " << colors.size() << std::endl;

This prints:

Removed: pink
Left: 2

If you try to store the result of pop_back() in a variable, std::string lastColor = colors.pop_back();, the program doesn't compile:

main.cpp:7:17: error: no viable conversion from 'void' to 'std::string' (aka 'basic_string<char>')

The message says that void can't be converted to std::string. void means “nothing”: pop_back() doesn't give any value, so there is nothing to store in the variable. You'll meet the word void again in the lesson on functions.

Never remove anything from an empty vector. There is nothing to remove, and the program may then behave unpredictably, just like with an index outside the vector.

Instructions

Ava's project is finished, and she is leaving the team. Store the last colleague in a std::string variable named leavingColleague (calculate the index with size() - 1). Then remove her from colleagues with pop_back().

Print who is leaving and how many colleagues remain, one below the other. The output should include the lines Leaving: Ava and Remaining: 3.

Start programming for free

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

Or sign up with:

7/10