Codiqo

Learn C++ · lesson 27 of 61 · about 7 minutes

Growing and Looping

Open the chest at the exit: add what the hero picks up with push_back, drop extras with pop_back, and show the bag with range-for.

What you'll learn

  • Add with push_back
  • Remove with pop_back
  • Loop with range-for and by index

The chest at the exit

By the exit stands a chest. The hero picks things up one word at a time until typing done, and each one goes on the end of the bag with push_back. The bag only holds 5 things, so while it has more, the last thing packed is left behind with pop_back. A small function, showBag, prints the bag with a range-for, and it takes the vector by const& so nothing is copied or changed.

Grow and shrink

  • v.push_back(x) adds x to the end
  • v.pop_back() removes the last item
  • v.empty() is true when there are no items
  • for (int x : v) visits every item; for (int& x : v) lets you change them

A growing list

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> queue;
    queue.push_back("Ada");
    queue.push_back("Bo");
    queue.push_back("Cy");
    queue.pop_back();
    for (const std::string& name : queue) std::cout << name << " ";
    std::cout << "(" << queue.size() << ")\n";

    std::vector<int> prices = {3, 7, 2};
    for (int& p : prices) p *= 2;
    int total = 0;
    for (int p : prices) total += p;
    std::cout << total << "\n";
}

Output

Ada Bo (2)
24

Tip

In a range-for, a plain variable is a copy. Add & to change the items themselves, or const & to read big items without copying them.

Tip

Pass a vector to a function as const std::vector<T>& when the function only reads it: a plain std::vector<T> parameter would copy every item first.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.