C++ Map
A map stores pairs of a key and a value: a word and its meaning, a name and a phone number, a product and its stock. Each key appears once, and looking up a key is fast. std::map keeps the keys sorted; std::unordered_map keeps no order but is usually faster.
Adding and reading
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> stock;
stock["mango"] = 12;
stock["apple"] = 30;
stock["banana"] += 5; // a missing key starts at 0
stock["apple"] -= 4;
for (const auto& [fruit, count] : stock) { // sorted by key
std::cout << fruit << ": " << count << "\n";
}
std::cout << stock.size() << " kinds\n";
return 0;
}apple: 26 banana: 5 mango: 12 3 kinds
m[key] returns the value for a key, creating the key with a default value (0 for numbers, empty for strings) if it is missing. That is handy for counting, but it means just reading m["kiwi"] adds kiwi to the map.
Looking up safely
To check without adding, use contains (C++20), count or find. at(key) reads an existing key and throws std::out_of_range if it is missing.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> capitals = {
{"India", "New Delhi"}, {"Japan", "Tokyo"}, {"France", "Paris"}
};
for (std::string country : {"Japan", "Peru"}) {
auto it = capitals.find(country);
if (it != capitals.end()) {
std::cout << country << ": " << it->second << "\n";
} else {
std::cout << country << ": not known\n";
}
}
std::cout << std::boolalpha << capitals.contains("India") << "\n";
return 0;
}Japan: Tokyo Peru: not known true
An iterator to a map element points at a pair: it->first is the key, it->second the value.
Counting words
#include <iostream>
#include <map>
#include <sstream>
#include <string>
int main() {
std::string text = "the cat and the dog and the bird";
std::map<std::string, int> count;
std::istringstream in(text);
std::string word;
while (in >> word) count[word]++;
for (const auto& [w, n] : count) std::cout << w << " " << n << "\n";
return 0;
}and 2 bird 1 cat 1 dog 1 the 3
std::istringstream (from sstream) reads words from a string the way cin reads from the keyboard.
unordered_map
std::unordered_map has the same operations but stores keys in a hash table: lookups are very fast on average, and the order of the keys when looping is unpredictable. Use it for large maps where order does not matter, std::map when you want sorted output.
Practice exercises
- Store a small phone book and look up a name the user types.
- Count how many times each letter appears in a sentence and print the counts in alphabetical order.
- Remove all entries whose value is 0 from a map of stock counts.