std::map is a sorted key-value store (red-black tree, O(log n)). std::unordered_map is a hash table (O(1) average). Include <map> and <unordered_map> respectively.
Include: #include <map> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::map<K,V> | class template | Sorted associative container |
| std::unordered_map<K,V> | class template | Hash-based associative container |
| m[key] | V & | Access/insert by key |
| m.at(key) | V & | Access by key; throws if absent |
| m.insert({k,v}) | pair<it,bool> | Insert key-value pair |
| m.emplace(k,v) | pair<it,bool> | Construct pair in-place |
| m.erase(key) | size_t | Remove element by key |
| m.find(key) | iterator | Iterator to key or m.end() |
| m.count(key) | size_t | Count of key (0 or 1 for map) |
| m.contains(key) | bool | True if key exists (C++20) |
| m.size() | size_t | Number of key-value pairs |
| m.empty() | bool | True if map has no elements |
| m.clear() | void | Remove all elements |
| m.lower_bound(key) | iterator | First element >= key (map only) |
| m.upper_bound(key) | iterator | First element > key (map only) |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <map>
#include <unordered_map>
#include <string>
using namespace std;
int main() {
map<string, int> scores;
scores["Alice"] = 95; scores["Bob"] = 87;
scores["Carol"] = 92; scores["Dave"] = 78;
cout << "Sorted scores:\n";
for (auto &[name, score] : scores)
cout << " " << name << " : " << score << "\n";
scores.erase("Dave");
cout << "After erasing Dave, size=" << scores.size() << "\n";
unordered_map<string, int> word_count;
string text[] = {"apple","banana","apple","cherry","banana","apple"};
for (auto &w : text) word_count[w]++;
cout << "\nWord counts:\n";
for (auto &[word, cnt] : word_count)
cout << " " << word << " : " << cnt << "\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -o map_demo map_demo.cpp