Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Structured binding `const auto& [id, cand]` in a range-based `for` loop

Give the current `std::map` entry’s key and value separate names so you can read both in a range-based `for` loop without copying the pair.

Version: ISO C++23; implementation support may vary

Syntax

for (const auto& [id, cand] : candidates) {
    // Use id and cand for the current element.
}

“Wiązanie strukturalne const auto& [id,cand] w range-for” means a structured binding in a range-based for loop. In for (const auto& [id, cand] : candidates), the colon separates the declaration from the range. On each iteration, the declaration is initialized from the element obtained by dereferencing the current iterator. A std::map<Key, T> element is a std::pair<const Key, T>, so the binding needs two names: id names first (the key) and cand names second (the mapped value). Position, not spelling, determines which is which.

auto lets the compiler deduce the type. const auto& binds a hidden lvalue reference to the current pair as const, so the pair is not copied. In this example neither id nor cand can be assigned through those names; that does not make the map itself const.

For this map, auto [id, cand] copies the pair on each iteration, so changing cand changes only the copy. With a non-const map, auto& [id, cand] lets you change the mapped value through cand, but the key stays const. The names are in scope only within the current iteration. Do not use a saved reference to either component after the entry is erased or the map is destroyed.

This syntax has been available since C++17 and is valid in ISO C++23. Support can depend on the implementation and the selected compiler mode.

Examples

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<int, std::string> candidates{{42, "Mira"}, {7, "Lena"}};

    for (const auto& [id, cand] : candidates) {
        std::cout << id << ": " << cand << '\n';
    }
}

Result

7: Lena
42: Mira

The default comparator for `std::map<int, std::string>` orders keys numerically from smallest to largest. So `7: Lena` appears before `42: Mira`, even though `42` is listed first in the initializer.

Related lessons

  • C++ · Lesson 62 · Intermediate · Version: 2

Sources