Syntax
auto& [key, value] = entry;Examples
C++ structured bindings
Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.
#include <map>
#include <string>
#include <iostream>
int main() {
std::map<std::string, int> visits{{"Ada", 2}};
for (auto& [name, count] : visits) {
++count;
std::cout << name << ' ' << count << '\n';
}
std::cout << visits.at("Ada") << '\n';
}- Output: Ada 3, then 3. The reference binding changes the map value; the map key remains const.
Best practices
- Choose auto, auto& or const auto& deliberately. Reference bindings must not outlive the object they decompose.
Runtime & versions
Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ISO C++ resources