TExcelTAD
Home › C++ › C++ auto, Range-for & Structured Bindings

C++ auto, Range-for and Structured Bindings

C++11 and later standards added features that make everyday code dramatically shorter and safer. This lesson collects three of the most useful ones — auto, the range-based for loop and structured bindings — along with a few related helpers you will see in modern code.

auto: let the compiler deduce the type

With auto, the variable's type is deduced from its initialiser. It is still statically typed — the type is fixed at compile time, just not written out:

cpp · try it yourself
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;

int main() {
    auto count = 10;              // int
    auto ratio = 0.75;            // double
    auto label = string("ok");    // std::string
    auto letter = 'z';            // char

    map<string, vector<int>> scores = {{"ana", {90, 85}}, {"ben", {70}}};

    // without auto: map<string, vector<int>>::iterator it = scores.begin();
    auto it = scores.begin();
    cout << it->first << " has " << it->second.size() << " scores\n";

    cout << count * ratio << " " << label << " " << letter << "\n";
}
ana has 2 scores
7.5 ok z

auto drops references and top-level const. Add them back explicitly when you want them:

Declaration Deduced as
auto x = expr; a copy
auto& x = expr; a reference (can modify the original)
const auto& x = expr; a read-only reference (no copy)
auto&& x = expr; a "forwarding" reference — binds to anything

Tip: Use auto when the type is obvious from the right side or is long and noisy (iterators, lambdas). Spell the type out when it adds clarity, e.g. double total = 0;.

Range-based for, done right

You already know for (x : container). The choice of loop variable type matters:

cpp · try it yourself
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    vector<string> names = {"kim", "lou", "max"};

    for (auto n : names) n[0] = toupper(n[0]);         // copies: no effect
    for (const auto& n : names) cout << n << " ";
    cout << "\n";

    for (auto& n : names) n[0] = toupper(n[0]);        // references: modifies
    for (const auto& n : names) cout << n << " ";
    cout << "\n";

    // C++20: an init-statement in range-for
    for (int i = 1; const auto& n : names) {
        cout << i++ << "." << n << " ";
    }
    cout << "\n";
}
kim lou max
Kim Lou Max
1.Kim 2.Lou 3.Max

Rule of thumb: const auto& to read, auto& to modify, plain auto only for cheap types like int or when you deliberately want a copy.

Structured bindings

Structured bindings (C++17) unpack a pair, tuple, struct or array into separate named variables in one declaration:

cpp · try it yourself
#include <iostream>
#include <map>
#include <string>
#include <tuple>
using namespace std;

struct Point3 { double x, y, z; };

tuple<string, int, double> parseRecord() {
    return {"widget", 4, 2.5};
}

int main() {
    auto [name, qty, price] = parseRecord();
    cout << name << ": " << qty << " x " << price << "\n";

    Point3 p{1, 2, 3};
    auto& [x, y, z] = p;          // references to p's members
    z = 30;
    cout << p.x << "," << p.y << "," << p.z << "\n";

    map<string, int> population = {{"Lagos", 15}, {"Lima", 11}, {"Oslo", 1}};
    for (const auto& [city, millions] : population) {
        cout << city << " ~" << millions << "M\n";
    }

    if (auto [it, inserted] = population.insert({"Lima", 99}); !inserted) {
        cout << "Lima already present with " << it->second << "\n";
    }
}
widget: 4 x 2.5
1,2,30
Lagos ~15M
Lima ~11M
Oslo ~1M
Lima already present with 11

More modern helpers

A few more features that make code cleaner:

cpp · try it yourself
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
using namespace std;

// std::optional: "a value, or nothing"
optional<int> findIndex(const vector<string>& v, string_view target) {
    for (size_t i = 0; i < v.size(); i++) {
        if (v[i] == target) return static_cast<int>(i);
    }
    return nullopt;
}

// constexpr: computed at compile time when possible
constexpr int cube(int n) { return n * n * n; }

int main() {
    vector<string> langs = {"C", "C++", "Rust"};
    if (auto idx = findIndex(langs, "C++")) {
        cout << "C++ at index " << *idx << "\n";
    }
    cout << "Go found? " << boolalpha << findIndex(langs, "Go").has_value() << "\n";
    cout << findIndex(langs, "Go").value_or(-1) << "\n";

    constexpr int big = cube(12);           // evaluated by the compiler
    static_assert(big == 1728);
    cout << big << "\n";

    long long distance = 149'600'000;       // digit separators (C++14)
    cout << distance << " km\n";
}
C++ at index 1
Go found? false
-1
1728
149600000 km
Feature Standard What it gives you
auto, range-for, lambdas, nullptr C++11 less boilerplate, safer null pointers
digit separators 1'000'000, make_unique C++14 readability, safe allocation
structured bindings, optional, string_view, if-init C++17 expressive, efficient code
concepts, ranges, <=>, contains, designated initialisers C++20 simpler generic code and comparisons

Test yourself

Given vector<string> v;, which loop reads elements without copying them?

  1. for (auto s : v)
  2. for (const auto& s : v)
  3. for (auto* s : v)
  4. for (string s : v)

What does auto [a, b] = make_pair(1, 2.5); declare?

  1. One pair named a
  2. int a = 1 and double b = 2.5
  3. Two pairs
  4. An array

What does std::optional<int> represent?

  1. An int that defaults to 0
  2. Either an int or no value at all
  3. A pointer to int
  4. A list of ints