typestar

Range-based for in C++

The loop that walks a whole container with no index, no iterator, and no off-by-one.

#include <string>
#include <vector>

int count_spaces(const std::string &text) {
    int spaces = 0;
    for (char c : text) {
        if (c == ' ') {
            spaces++;
        }
    }
    return spaces;
}

int sum(const std::vector<int> &values) {
    int total = 0;
    for (const auto &value : values) {
        total += value;
    }
    return total;
}

How it works

  1. for (char c : text) visits every character of the string by value.
  2. for (const auto &value : values) borrows each element instead of copying it.
  3. Both loops just accumulate; the container's own bounds end the iteration.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
292
Tokens
90
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 2 of 3 in Control flow, step 5 of 27 in Language basics.

← Previous Next →