C++ Programming: Objects, RAII and the STL ยท The Standard Library
Key-value lookups with keys kept in sorted order, and loops with structured bindings.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> stock; // keys kept in sorted order
stock["pear"] = 2;
stock["apple"] = 5;
stock["apple"] += 3;
int kiwis = stock.count("kiwi"); // 0: not there
int total = 0;
for (const auto &[fruit, qty] : stock) {
total += qty;
}
cout << stock.size() << " " << kiwis << " " << total << endl;
return 0;
}stock is created on the stack with the value {}.stock changes from {pear: 2} to {apple: 5, pear: 2}.total is created on the stack with the value 0.fruit is created on the stack with the value "apple". qty is created on the stack with the value 8.fruit changes from "apple" to "pear". qty changes from 8 to 2.total changes from 8 to 10.fruit goes out of scope and disappears. qty goes out of scope and disappears.2 0 10.0.