cpp / intermediate
Snippet
Range-Based Loop with Structured Bindings
Structured bindings (C++17) allow you to unpack complex data structures like pairs or tuples directly into individual variables within a loop header. This significantly improves readability when iterating over associative containers like maps.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>#include <map>#include <string>int main() {std::map<std::string, int> inventory = {{"Apples", 50}, {"Oranges", 30}};// Structured bindings unpack map pairs into named variablesfor (const auto& [item, count] : inventory) {std::cout << item << ": " << count << " in stock" << std::endl;}return 0;}
Breakdown
1
for (const auto& [item, count] : inventory)
Iterates through the map, binding the key to 'item' and the value to 'count'.