typestar

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

  1. const auto &[name, count] splits each map entry as the range-for walks the sales.
  2. The function returns a std::pair built with brace init: {top, most}.
  3. auto [name, sold] unpacks the returned pair straight into two fresh names.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Modern touches, step 23 of 27 in Language basics.

← Previous Next →