A map stores key → value pairs. Instead of finding things by position number, you find them by a key, like a word or a name:
Think of it like this: A map is like a real dictionary: you look up a word (the key) and find its meaning (the value). Or a phone book: name → phone number.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> ages;
ages["Ana"] = 31;
ages["Ben"] = 25;
ages["Cleo"] = 40;
cout << "Ben is " << ages["Ben"] << "\n";
ages["Ben"] = 26; // change a value
cout << "Ben is now " << ages["Ben"] << "\n";
cout << "People: " << ages.size() << "\n";
return 0;
}Output
Ben is 25 Ben is now 26 People: 3
Does a key exist?
Use count(key): it is 1 if the key is there and 0 if not. (find works too.)
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, string> capitals = {{"France", "Paris"}, {"Japan", "Tokyo"}};
string country = "Japan";
if (capitals.count(country)) {
cout << "The capital of " << country << " is " << capitals[country] << "\n";
}
if (capitals.count("Peru") == 0) {
cout << "I don't know Peru's capital\n";
}
capitals.erase("France");
cout << capitals.size() << " left\n";
return 0;
}Output
The capital of Japan is Tokyo I don't know Peru's capital 1 left
Common mistake: Reading
m[key]for a key that isn't there creates it, with a value of 0 (or an empty string). Check withcountfirst if you only want to look.
Looping over a map
A map keeps its keys sorted. Each item is a pair of key and value:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> stock = {{"pears", 4}, {"apples", 10}, {"kiwis", 0}};
for (const auto& [fruit, count] : stock) {
cout << fruit << ": " << count << "\n";
}
return 0;
}Output
apples: 10 kiwis: 0 pears: 4
The counting trick
Because a missing key starts at 0, m[key]++ is a perfect way to count things:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
string text = "mississippi";
map<char, int> counts;
for (char c : text) {
counts[c]++;
}
for (const auto& [letter, n] : counts) {
cout << letter << " appears " << n << " times\n";
}
return 0;
}Output
i appears 4 times m appears 1 times p appears 2 times s appears 4 times
Tip:
unordered_map(from<unordered_map>) works the same way and is usually faster, but its keys come out in no particular order. Usemapwhen you want them sorted.