cpp / intermediate
Snippet
Decomposing Objects with Structured Bindings
Structured bindings allow you to unpack members of structs, pairs, or arrays into individual named variables in a single line. This improves readability and reduces boilerplate code when working with compound data types.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>#include <string>struct Player {int score;std::string nickname;};Player get_top_player() {return {999, "ProCoder"};}int main() {// Directly unpack struct members into local variablesauto [currentScore, currentName] = get_top_player();std::cout << currentName << " has " << currentScore << " points." << std::endl;return 0;}
Breakdown
1
auto [currentScore, currentName] = get_top_player();
Unbinds the fields of the Player struct into two new variables, currentScore and currentName.
2
std::string nickname;
The target struct member that gets mapped to the second binding variable.