C++ Tutorial · Standard Library · Lesson 16 of 21
C++ Maps and Sets
std::map, std::unordered_map, std::set and structured bindings.
Maps
std::map— keys kept sorted (balanced tree, O(log n)).std::unordered_map— hash table, average O(1), no order.
Structured bindings (auto [key, value]) make iteration clean:
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
int main() {
std::map<std::string, int> stock{{"pears", 2}, {"apples", 5}};
stock["plums"] = 12;
stock["apples"] += 3;
for (const auto& [fruit, qty] : stock) std::cout << fruit << '=' << qty << ' ';
std::cout << '\n';
std::cout << std::boolalpha << stock.contains("kiwis") << '\n';
std::unordered_map<std::string, int> counts;
for (const std::string w : {"the", "cat", "the", "hat"}) counts[w]++;
std::cout << counts["the"] << ' ' << counts.size() << '\n';
std::set<int> unique{3, 1, 3, 2, 1};
for (int n : unique) std::cout << n << ' ';
std::cout << '\n';
}
Output
apples=8 pears=2 plums=12 false 2 3 1 2 3
Run this on your computer — see “Get Started” for setup.
Sets
std::set and std::unordered_set store unique values.
Test yourself
Which container keeps its keys sorted?
std::unordered_mapstd::mapstd::vectorstd::unordered_set
Show answer
Answer: std::map