Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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().

  2. 2

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

Back

7/10

  1. 1. Creating a Vector
  2. 2. Reading Elements
  3. 3. Changing Elements
  4. 4. Size and the Last Element
  5. 5. Index Out of Range
  6. 6. Adding Elements: push_back()
  7. 7. Removing Elements: pop_back()
  8. 8. Nested Vectors
  9. 9. Characters of a Text
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.