Library contents

C++ std::map structured bindings

Visit both the label and count of each shelf and print them in aisle order.

A simple example

std::map structured bindings

  1. Start with B = 2, A = 1
  2. Do this Visit entries in key order
  3. Result A = 1, then B = 2
Ordering the keys before visiting them gives a predictable sequence.

Syntax

C++ syntax
for (const auto& [key, value] : stock)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Print shelf totals in aisle order

A stockroom supervisor sends a short inventory message each evening. Both the aisle name and its count belong on each line, and the message must follow aisle order every time.

From the programstd::cout << separator << aisle << "=" << count
ResultA=4, B=2
lesson.cpp
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> stock{{"B", 2}, {"A", 4}};
    std::string separator;
    for (const auto& [aisle, count] : stock) {
        std::cout << separator << aisle << "=" << count;
        separator = ", ";
    }
    return 0;
}
Output
A=4, B=2

The report prints A with its four items before B with its two.

Advertisements

Print stock by aisle

A delivery entered the second aisle before the first. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?

GivenB → 3 · A → 2
Worked resultA 2 · B 3

Print counts by room

A teacher recorded West before East during the count. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?

GivenWest → 8 · East → 4
Worked resultEast 4 · West 8

What to watch for

The default std::map comparator orders keys. unordered_map has different iteration guarantees.

Documentation for std::map structured bindings