Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 20 min

std::vector, the array that grows

By the end of this chapter, you'll be able to

  • Create a std::vector and add items to it with push_back
  • Access an item by its index and get the size with size()
  • Go through a vector with a range-based for loop
  • Choose between [] and at() to access items

Creating and filling a vector

#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores = {120, 85, 240};
    scores.push_back(310);                 // adds at the end
    std::cout << "Number of scores: " << scores.size() << "\n";
    std::cout << "First: " << scores[0] << ", last: " << scores.back() << "\n";
    scores[1] = 90;                        // changes the second one
    std::cout << "Second: " << scores[1] << "\n";
    return 0;
}
Number of scores: 4
First: 120, last: 310
Second: 90
  • std::vector<int> reads "vector of integers": the type of the items is written between angle brackets. You need #include <vector>.
  • push_back(value) adds an item at the end; the vector grows by itself.
  • scores[i] accesses the item at index i. As with arrays, indexes go from 0 to size() - 1.
  • size() gives the number of items, back() the last one, empty() tells whether the vector is empty.

Going through a vector

The range-based for loop goes through each item, with no index and no risk of going too far:

No more items: the loop stops and we display the total.

Step 7 of 7
Text description of the animation
  1. We add up the week's expenses.
  2. The vector holds three items.
  3. total starts at 0.
  4. First round: e receives a copy of the first item, 12.5, added to the total.
  5. Second round: e is 30, total becomes 42.5.
  6. Third round: e is 7.5, total becomes 50.
  7. No more items: the loop stops and we display the total.

When you need the index, use a classic for. The type of the index is then std::size_t, the positive integer type of size(): comparing an int with size() triggers a warning (comparison of integer expressions of different signedness).

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

int main() {
    std::vector<std::string> cities = {"Abidjan", "Montreal", "Hanoi"};
    for (std::size_t i = 0; i < cities.size(); i++) {
        std::cout << i + 1 << ". " << cities[i] << "\n";
    }
    for (std::string& c : cities) {
        c += "!";                          // &: we change the real items
    }
    std::cout << cities[0] << "\n";
    return 0;
}
1. Abidjan
2. Montreal
3. Hanoi
Abidjan!

In for (std::string& c : cities), the & makes c a reference: another name for the item itself, not a copy. Changing it therefore changes the vector. Without &, you'd change a copy, immediately forgotten. We'll come back to references in the next course.

Your turn

Worked exercise

Worked exercise: temperature statistics

Read temperatures from the keyboard until the end of input and store them in a std::vector<double>. Then display the number of readings, the lowest, the highest and the average. If no value was read, display No readings.

Hint 1
while (std::cin >> t) { temps.push_back(t); } fills the vector.
Hint 2
Initialise the minimum and the maximum with the first item, temps[0], after checking that the vector isn't empty.
Show the solution and common mistakes
#include <iostream>
#include <vector>

int main() {
    std::vector<double> temps;
    double t = 0;
    while (std::cin >> t) {
        temps.push_back(t);
    }
    if (temps.empty()) {
        std::cout << "No readings\n";
        return 0;
    }
    double lowest = temps[0], highest = temps[0], sum = 0;
    for (double x : temps) {
        if (x < lowest) lowest = x;
        if (x > highest) highest = x;
        sum += x;
    }
    std::cout << temps.size() << " readings, min " << lowest << ", max " << highest
              << ", average " << sum / temps.size() << "\n";
    return 0;
}
21.5 24 19.5 26 23
5 readings, min 19.5, max 26, average 22.8

Common mistakes:

  • Initialising lowest to 0: with temperatures that are all positive, the minimum displayed would be 0, a value that was never recorded.
  • Reading temps[0] without checking empty(): on an empty vector, it's an out-of-bounds access.

Summary

  1. 1std::vector<T> is a list of items of type T that grows with push_back.
  2. 2Indexes go from 0 to size() - 1; [] checks nothing, at() checks and throws an exception.
  3. 3for (T x : v) goes through each item; for (T& x : v) lets you change them.
  4. 4With an index, use std::size_t to compare it with size().
  5. 5Check empty() before accessing the first item.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.