On this page
Structured Bindings
Prev: nullptr | Up: builtins | Next: Move Semantics
Rel: auto, std::unordered_map
Ref: cppreference — Structured Binding
Tags: #public #prog #cpp #builtins #tier/core
Overview
Structured bindings (C++17) unpack the members of a struct, std::pair, std::tuple, or fixed-size array into named local variables in a single declaration.
Notes & Pitfalls
- C++17 tuple/struct/pair unpacking: Use
const auto& [k, v]in range-forloops overstd::mapto avoid copying keys and values. - Works on plain aggregate structs,
std::pair,std::tuple, and C arrays.
Example
#include <cassert>
#include <map>
#include <string>
int main() {
std::map<std::string, int> scores{{"ada", 100}, {"bob", 90}};
int total = 0;
for (const auto& [name, score] : scores) {
total += score;
}
assert(total == 190);
}
Linked from
Related notes
- tuts/cpp/builtins/auto Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/move_semantics Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/nullptr Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/stdlib/containers/unordered_map Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/containers links to this page; shared tags: #cpp, #prog
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/classes_and_virtual shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/concepts shared tags: #builtins, #cpp, #prog, #tier