Structured bindings in C++
Unpack pairs and map entries into named variables — no more .first and .second.
#include <map>
#include <string>
#include <utility>
std::pair<std::string, int> best_seller(
const std::map<std::string, int> &sales) {
std::string top;
int most = -1;
for (const auto &[name, count] : sales) {
if (count > most) {
top = name;
most = count;
}
}
return {top, most};
}
// unpack the winning pair
auto [name, sold] = best_seller({{"tea", 40}, {"coffee", 55}});
How it works
const auto &[name, count]splits each map entry as the range-for walks the sales.- The function returns a
std::pairbuilt with brace init:{top, most}. auto [name, sold]unpacks the returned pair straight into two fresh names.
Keywords and builtins used here
autoconstforifintreturn
The run, in numbers
- Lines
- 19
- Characters to type
- 374
- Tokens
- 119
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 95 seconds.
Step 2 of 3 in Modern touches, step 23 of 27 in Language basics.