C++ · STL: map and unordered_map
Ordered std::map (a balanced tree) versus std::unordered_map (a hash table), lookups with find/count, and the operator[] side effect.
C++ has two kinds of dictionary:
std::map | std::unordered_map | |
|---|---|---|
| structure | balanced binary tree | hash table |
| lookup | O(log n) | O(1) average |
| iteration order | sorted by key | unspecified |
The trap: m[key] inserts a default-constructed value if the key is missing. To just check, use find() or count() (or contains() in C++20). That’s the opposite of Python, where d[k] raises an error instead.
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
int main() {
std::map<std::string, int> marks{{"python", 95}, {"maths", 88}, {"cpp", 81}};
for (const auto& [subject, m] : marks) // sorted by key
std::cout << subject << ": " << m << '\n';
std::cout << "size before: " << marks.size();
int x = marks["physics"]; // inserts physics=0!
std::cout << ", after operator[]: " << marks.size() << " (value " << x << ")\n";
if (auto it = marks.find("chemistry"); it == marks.end())
std::cout << "chemistry not found, size still " << marks.size() << '\n';
std::unordered_map<std::string, int> freq;
std::istringstream text("to be or not to be");
for (std::string w; text >> w;) ++freq[w]; // here insert-on-miss is handy
std::cout << "to=" << freq["to"] << " be=" << freq["be"] << " or=" << freq["or"] << '\n';
}
Output:
cpp: 81
maths: 88
python: 95
size before: 3, after operator[]: 4 (value 0)
chemistry not found, size still 4
to=2 be=2 or=1Sources
- std::map — cppreference.com
- std::unordered_map — cppreference.com
- std::map::operator[] — cppreference.com