Legacy C++ › 6. The Standard Template Library
Associative Containers
set, map, multiset, multimap and ordering requirements.
intermediate #stl#map#set#multimap#multiset#ordering
Explanation
Associative containers keep elements sorted by key in a balanced binary tree (usually a red-black tree). Lookup, insertion and deletion are all O(log n).
| Container | Holds | Duplicate keys |
|---|---|---|
std::set<K> |
keys only | no |
std::multiset<K> |
keys only | yes |
std::map<K,V> |
std::pair<const K, V> |
no |
std::multimap<K,V> |
std::pair<const K, V> |
yes |
Keys are ordered by std::less<K> (the < operator) unless you supply another comparator. Two keys are equivalent if neither is less than the other, not if ==.
map::operator[]inserts a default-constructed value if the key is missing.find(key)returnsend()if absent, andcount(key)returns 0 or 1 (more for multi).insertreturnspair<iterator,bool>(the bool tells you if it was newly inserted).- Iterating yields keys in sorted order. Keys are
const; you cannot change them in place.
Example
#include <iostream>
#include <map>
#include <set>
#include <string>
int main() {
std::map<std::string, int> stock;
stock["apple"] = 5;
stock["banana"] = 2;
stock.insert(std::make_pair("cherry", 9));
stock["apple"] += 10; // operator[] finds the entry
std::map<std::string, int>::iterator it = stock.find("banana");
if (it != stock.end()) std::cout << it->first << " has " << it->second << "\n";
std::cout << stock["durian"] << "\n"; // inserts durian -> 0 !
std::cout << "size: " << stock.size() << "\n"; // 4
for (std::map<std::string, int>::const_iterator i = stock.begin(); i != stock.end(); ++i)
std::cout << i->first << "=" << i->second << " "; // sorted by key
std::cout << "\n";
std::set<int> s;
s.insert(3); s.insert(1); s.insert(3); // duplicate ignored
std::cout << s.size() << " " << (s.count(1) ? "has 1" : "no 1") << "\n";
std::multimap<std::string, int> tags;
tags.insert(std::make_pair("c++", 1));
tags.insert(std::make_pair("c++", 2));
std::cout << tags.count("c++") << "\n"; // 2
return 0;
}
Common pitfalls
m[key]in a lookup silently inserts. Usefind(orcount) to test for existence.- Keys of a custom type need a strict weak ordering: a sloppy
<=comparator breaks the tree. - You cannot modify a key through an iterator (it is
const); erase and reinsert. - Erasing during iteration: use
m.erase(it++)(post-increment) in C++03 for node-based containers. - Comparing C-string keys (
std::map<const char*, int>) compares addresses. Usestd::string.
Legacy vs modern
C++11 adds unordered_map/unordered_set (hash tables, average O(1)), emplace, at() for map, try_emplace/insert_or_assign (C++17) and contains (C++20). C++23’s flat_map stores keys in contiguous memory.
Exercises
1. Count word frequencies from a list of words.
std::map<std::string,int> freq;
for (std::size_t i = 0; i < words.size(); ++i) ++freq[words[i]];