Maps
A vector finds a value by its position, like scores[0] or scores[1]. But often you want to find a value by a name. How many pens are in stock? What does an apple cost? For this, C++ has the map.
A map stores key-value pairs. The key is what you look up with, for example the word "pens". The value is what you get back, for example 12. Each key appears only once in a map. Inside the map, each key and its value are kept together as a pair, like the ones from the last lesson. To use maps, add #include <map> at the top.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> stock;
stock["pens"] = 12;
stock["ink"] = 3;
stock["paper"] = 40;
cout << stock["ink"] << "\n";
stock["ink"] = 2;
cout << stock["ink"] << "\n";
return 0;
}
Output:
3
2
map<string, int> names two types: the keys are strings and the values are ints. The square brackets take a key, not a position. stock["pens"] = 12 adds the key pens with the value 12. stock["ink"] reads the value of ink. If you assign to a key that already exists, the new value replaces the old one. That is why ink changed from 3 to 2.
Looping over a map
A range-based for loop visits every pair in the map:
map<string, int> stock;
stock["pens"] = 12;
stock["ink"] = 3;
stock["paper"] = 40;
for (auto& item : stock) {
cout << item.first << ": "
<< item.second << "\n";
}
Output:
ink: 3
paper: 40
pens: 12
Each item is one pair, so item.first is the key and item.second is the value. As in the Pairs lesson, auto& saves you from writing the long type and stops the loop from copying each pair.
Look at the order: ink, paper, pens. We added pens first, but the map printed the keys in alphabetical order. A map always keeps its keys sorted. This also helps it find a key quickly, even in a big map.
A structured binding from the Pairs lesson can give the key and the value their own names:
for (auto& [name, count] : stock) {
cout << name << " = " << count << "\n";
}
Output:
ink = 3
paper = 40
pens = 12
Reading a missing key
What happens if you read a key that is not in the map?
cout << "size before: " << stock.size() << "\n";
cout << stock["glue"] << "\n";
cout << "size after: " << stock.size() << "\n";
Output:
size before: 3
0
size after: 4
There was no error. Reading stock["glue"] added a new key glue with the value 0, and the size went from 3 to 4. This is handy when you count things: counts[word]++ starts every new word at 0 and adds 1. But it is a problem when you only want to check whether a key exists.
To check without adding anything, use count. It returns 1 if the key is in the map and 0 if it is not:
cout << stock.count("pens") << "\n";
cout << stock.count("tape") << "\n";
cout << "size: " << stock.size() << "\n";
Output:
1
0
size: 4
tape is not in the map, and the size is still 4.
In the exercise, add two fruits to a price list and look up the price of the fruit that is typed in.