Structured Bindings in C++

Level 5404 keystrokes

C++17 structured bindings unpack map entries into name and score, a struct into its three members, and the pair returned by insert() into an iterator and a bool.

C++ code

// Simple struct with three public members
1struct Point {
2 double x, y, z;
3};
4
// map keeps its keys sorted
5map<string, int> scores = {{"Alice", 95}, {"Bob", 87}, {"Carol", 92}};
6
// Each element is a pair, split into key and value
7for (const auto& [name, score] : scores) {
// Prints in key order: Alice, Bob, Carol
8 cout << name << ": " << score << endl;
9}
10
// Aggregate initialization of the struct
11Point p = {1.5, 2.5, 3.5};
// Unpacks the members x, y, z in declaration order
12auto [px, py, pz] = p;
// Prints "Point: (1.5, 2.5, 3.5)"
13cout << "Point: (" << px << ", " << py << ", " << pz << ")" << endl;
14
// insert returns pair<iterator, bool>; the bool says whether the key was new
15auto [it, inserted] = scores.insert({"Dave", 88});
// "Dave" was new, so it prints "Inserted: 1" (true without boolalpha)
16cout << "Inserted: " << inserted << endl;

Output

Alice: 95
Bob: 87
Carol: 92
Point: (1.5, 2.5, 3.5)
Inserted: 1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 31
  • "× 20
  • ,× 17
  • ;× 9
  • {× 8
  • }× 8
  • :× 4
  • .× 4
  • =× 4
  • (× 3

More C++ examples at level 5

← C++ typing practice