SyntaxPilot
Courses/C++/Lesson 33
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 33 of 40

Modern C++: auto, range-for, structured bindings

queued

These are the notes for C++ episode 33. Long iterator types are painful to type and easy to get wrong. This episode shows one wrong word producing a wall of errors, then builds three modern C++ features as the fix: auto (C++11) lets the compiler work out a type, the range-based for loop (C++11) visits every element without a counter, and structured bindings (C++17) give the parts of a pair real names. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; outputs and error messages are copied from those runs.

The problem: a long type, typed by hand

A chai stall keeps its menu in a map (episode 23) and prints it with an iterator (episode 26):

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    for (map<string, int>::iterator it = menu.begin();
         it != menu.end(); ++it)
        cout << it->first << ": Rs " << it->second << endl;
    return 0;
}

Output:

chai: Rs 15
coffee: Rs 30
samosa: Rs 20

(A map keeps its keys sorted, so the items come out in alphabetical order.) Now someone changes int to double, but only in the loop:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    for (map<string, double>::iterator it = menu.begin();
         it != menu.end(); ++it)
        cout << it->first << ": Rs " << it->second << endl;
    return 0;
}

g++ prints a wall of errors, starting with:

main.cpp:8:55: error: conversion from '_Rb_tree_iterator<pair<[...],int>>' to non-scalar type '_Rb_tree_iterator<pair<[...],double>>' requested
main.cpp:9:13: error: no match for 'operator!=' (operand types are 'std::map<std::__cxx11::basic_string<char>, double>::iterator' ...

Why: we were copying out a type the compiler already knew. menu.begin() can only return one type; typing it again is busywork, and every copy can be wrong.

Step 1: auto

At the stall In C++
The order is already written on the slip: "2 masala chai" the initializer, the value after =, already has a type
The waiter reads the slip instead of asking again auto: the compiler reads the type from the initializer
It's still exactly 2 masala chai, nothing guessed the type is fixed at compile time, exactly what you'd have typed
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    for (auto it = menu.begin(); it != menu.end(); ++it)
        cout << it->first << ": Rs " << it->second << endl;
    return 0;
}

Output: the same menu. If the map ever changes, the loop follows automatically.

auto is not a "holds anything" type (C++ is still statically typed). It's type deduction: the compiler fills in one exact type, once, at compile time.

The auto + text trap

#include <iostream>
#include <string>
using namespace std;

int main() {
    auto cups = 3;                   // int
    auto price = 12.5;               // double
    auto item = "chai";              // ???
    cout << cups * price << endl;
    cout << item << " has " << item.size() << " letters" << endl;
    return 0;
}
main.cpp:10:37: error: request for member 'size' in 'item', which is of non-class type 'const char*'

Text in double quotes is a string literal, an old C-style string: an array of char that becomes a const char* (a pointer to characters). It isn't a std::string, so it has no .size(). auto copies exactly what's on the right. Say what you want:

#include <iostream>
#include <string>
using namespace std;

int main() {
    auto cups = 3;                   // int
    auto price = 12.5;               // double
    auto item = string("chai");      // string
    cout << cups * price << endl;
    cout << item << " has " << item.size() << " letters" << endl;
    return 0;
}

Output:

37.5
chai has 4 letters

(You can also write auto item = "chai"s; after using namespace std;: the s suffix makes a std::string.)

auto needs an initializer

auto total;
error: declaration of 'auto total' has no initializer

No value, nothing for the compiler to read the type from. Write auto total = 0; (an int) or just int total;.

Step 2: the range-based for loop

In class In C++
"Roll number 1, 2, 3..." : the teacher counts, and can go one too far for (int i = 0; i < v.size(); i++)
"Everyone on the list, one by one" : no numbers to manage for (int p : prices) : "for each p in prices"
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> prices = {15, 30, 20};     // chai, coffee, samosa
    for (int i = 0; i < prices.size(); i++)
        cout << prices[i] << " ";
    cout << endl;

    for (int p : prices)                   // for each p in prices
        cout << p << " ";
    cout << endl;
    return 0;
}

Output:

15 30 20 
15 30 20 

It works on every container (vector, list, deque, set, map, ...), plain arrays and strings: anything with begin() and end().

Changes to a copy are lost

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> prices = {15, 30, 20};     // chai, coffee, samosa
    for (auto p : prices)
        p += 5;                            // milk got costlier

    for (auto p : prices)
        cout << p << " ";
    cout << endl;
    return 0;
}

Output: 15 30 20 (unchanged!). Each time round, p is a copy of the element, like a photocopy of the menu: we changed the photocopy. Make p a reference (episode 10) with &:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> prices = {15, 30, 20};     // chai, coffee, samosa
    for (auto& p : prices)
        p += 5;                            // milk got costlier

    for (auto p : prices)
        cout << p << " ";
    cout << endl;
    return 0;
}

Output: 20 35 25.

Read big things with const auto&

Copying a long string on every pass costs time. const auto& is a reference (no copy) that you can't change by mistake:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    vector<string> orders = {"masala chai with extra ginger",
                             "filter coffee, less sugar",
                             "two samosas and green chutney"};
    for (const auto& o : orders)       // no copy, read only
        cout << o.size() << " letters: " << o << endl;

    for (const auto& o : orders)
        o += "!";
    return 0;
}
main.cpp:14:11: error: no match for 'operator+=' (operand types are 'const std::__cxx11::basic_string<char>' and 'const char [2]')

Without those two lines:

29 letters: masala chai with extra ginger
25 letters: filter coffee, less sugar
29 letters: two samosas and green chutney
Loop variable Copies? Can change the element? Use for
auto x yes no (changes a copy) small values: int, double, char
auto& x no yes changing every element
const auto& x no no reading strings, structs, anything bigger

Step 3: structured bindings

A range-for over a map gives pairs, with parts called first and second:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    for (const auto& p : menu)
        cout << p.first << ": Rs " << p.second << endl;
    return 0;
}

It works, but first and second say nothing. Like a two-part tiffin box: "top part" and "bottom part" don't help; when you unpack it you name things, "rice" and "dal". C++17 structured bindings unpack a pair (or a struct, array or tuple) into names you choose:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    for (const auto& [item, price] : menu)
        cout << item << ": Rs " << price << endl;
    return 0;
}

Output: the same menu, and the loop reads like English.

Two return values, two names

map::insert returns a pair<iterator, bool>: where the element is, and whether it was really added.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    auto [it, added] = menu.insert({"vada pav", 25});
    cout << it->first << (added ? " added" : " already there") << endl;

    auto [it2, added2] = menu.insert({"chai", 99});
    cout << it2->first << (added2 ? " added" : " already there")
         << ", still Rs " << it2->second << endl;
    return 0;
}

Output:

vada pav added
chai already there, still Rs 15

A map's keys are unique, so the second insert was refused, and added2 says so.

if with an initializer (C++17)

if (init; condition) declares a variable that exists only inside that if and its else:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    string want;
    while (cin >> want) {
        if (auto it = menu.find(want); it != menu.end())
            cout << want << ": Rs " << it->second << endl;
        else
            cout << want << ": not on the menu" << endl;
    }
    return 0;
}

Input: coffee dosa

Output:

coffee: Rs 30
dosa: not on the menu

One name per part

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> menu = {{"chai", 15}, {"coffee", 30}, {"samosa", 20}};
    for (const auto& [item, price, stock] : menu)
        cout << item << ": Rs " << price << endl;
    return 0;
}
main.cpp:8:22: error: 3 names provided for structured binding
main.cpp:8:22: note: while 'const std::pair<const std::__cxx11::basic_string<char>, int>' decomposes into 2 elements

When to use auto

  • Long or obvious types: iterators, make_unique<...>, lambdas, map::insert results.
  • Not where the type tells the reader something: int count = 0; is clearer than auto count = 0;.
  • Watch string literals: auto s = "text"; is a const char*.
  • In range-for: plain auto for small values, auto& to change, const auto& to read.

Common mistakes

Mistake Real g++ message / result Fix
auto item = "chai"; item.size(); error: request for member 'size' in 'item', which is of non-class type 'const char*' auto item = string("chai");
auto total; error: declaration of 'auto total' has no initializer auto total = 0;
for (auto p : prices) p += 5; compiles; prices unchanged for (auto& p : prices)
for (const auto& o : orders) o += "!"; error: no match for 'operator+=' (o is const) auto& if you really mean to change it
auto [item, price, stock] = *menu.begin(); error: 3 names provided for structured binding one name per part: auto [item, price]
a hand-typed iterator type that doesn't match error: conversion from '_Rb_tree_iterator<...int>>' to non-scalar type '..._Rb_tree_iterator<...double>>' requested auto it = menu.begin();

Mini project: chai loyalty card

Count each customer's visits, report repeat sign-ups using insert's added flag, print with structured bindings, and use if with an initializer:

#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> signups = {"Asha", "Ravi", "Meera", "Ravi", "Asha", "Ravi"};

    map<string, int> visits;
    int repeats = 0;
    for (const auto& name : signups) {
        auto [it, added] = visits.insert({name, 0});
        if (!added) repeats++;
        it->second++;                      // count this visit
    }

    for (const auto& [name, count] : visits)
        cout << name << ": " << count << " visit(s)" << endl;
    cout << "Repeat sign-ups: " << repeats << endl;

    if (auto it = visits.find("Ravi"); it != visits.end() && it->second >= 3)
        cout << "Ravi gets a free chai!" << endl;
    return 0;
}

Output:

Asha: 2 visit(s)
Meera: 1 visit(s)
Ravi: 3 visit(s)
Repeat sign-ups: 3
Ravi gets a free chai!

Practice

  1. Rewrite an old iterator loop over a map<string, int> of marks with auto and a range-for with structured bindings.
  2. Double every mark in a vector<int> with auto&.
  3. Print a map of students and marks with [name, marks].
  4. Use auto [it, added] to count duplicate names (the mini project above).
Solutions

Exercises 1 and 3:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> marks = {{"Asha", 91}, {"Ravi", 78}, {"Meera", 95}};

    // old way
    for (map<string, int>::iterator it = marks.begin(); it != marks.end(); ++it)
        cout << it->first << " " << it->second << endl;

    // modern way
    for (const auto& [name, m] : marks)
        cout << name << " " << m << endl;
    return 0;
}

Output:

Asha 91
Meera 95
Ravi 78
Asha 91
Meera 95
Ravi 78

Exercise 2:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> marks = {35, 42, 48};
    for (auto& m : marks)
        m *= 2;
    for (auto m : marks)
        cout << m << " ";
    cout << endl;
    return 0;
}

Output: 70 84 96

Quick quiz

What does this print?

vector<int> v = {1, 2, 3};
for (auto x : v)  x *= 10;
for (auto& x : v) x += 1;
for (auto x : v)  cout << x << " ";
Answer

2 3 4. The first loop multiplies copies, so v stays 1 2 3; the second uses auto&, so v really becomes 2 3 4.

Interview questions

  1. What does auto deduce for auto s = "hi";? const char*, not std::string.
  2. Does auto make C++ dynamically typed? No. The type is deduced once at compile time and never changes.
  3. Why didn't my range-for change the vector? The loop variable was a copy (auto x); use auto& x.
  4. Why const auto& in a range-for? No copy of each element (faster for strings and objects), and no accidental changes.
  5. What is a structured binding? C++17 syntax, auto [a, b] = expr;, that unpacks a pair, tuple, array or simple struct into named variables.
  6. What does map::insert return? A pair<iterator, bool>: the element's position and whether it was inserted.
  7. What is if (init; cond)? C++17 if with an initializer: the variable's scope is limited to the if/else.
  8. Does auto drop const and references? Yes, plain auto copies the value (dropping top-level const and &); write const auto& or auto& to keep them.

Glossary

Term Meaning, with an example
modern C++ The features added from C++11 onwards (C++11, 14, 17, 20...).
C++11 / C++17 Versions of the C++ standard; -std=c++17 tells g++ which one to use.
auto Let the compiler deduce a variable's type from its initializer: auto it = menu.begin();
type deduction The compiler working out a type from a value.
initializer The value a variable starts with, after =.
iterator An object that points at an element of a container and can move to the next (episode 26).
string literal Text in double quotes, "chai": a C-style const char*, not a std::string.
const char* A pointer to read-only characters: the type of an old C string.
range-based for for (auto x : container): visits every element, no counter.
range Anything with begin() and end(): containers, arrays, strings.
copy A separate duplicate; changing it doesn't change the original.
reference (&) Another name for an existing object: auto& p changes the real element.
const auto& A read-only reference: no copy, no changes.
pair Two values together, first and second; each map element is a pair<const Key, Value>.
structured binding auto [a, b] = pair; unpacks the parts into named variables (C++17).
decompose Split an object into its parts for a structured binding.
map::insert Adds a key/value if the key is new; returns pair<iterator, bool>.
if with initializer if (auto it = m.find(k); it != m.end()): a variable that lives only in the if.
scope The region of code where a name exists.

Summary

  • auto lets the compiler fill in a type from the initializer; it's still one fixed type.
  • auto x = "text" is a const char*; auto always needs an initializer.
  • Range-for: for (auto x : v); plain auto is a copy, auto& changes the original, const auto& reads without copying.
  • Structured bindings: auto [key, value] names the parts of a pair, one name per part.
  • if (init; condition) keeps a helper variable local.

Next episode: your laptop has several CPU cores, but every program so far used only one. Multithreading.