C++ Tutorial
C++ Map
map stores key-value pairs in order. Lookup by key instead of scanning a list.
Lookup by key
A vector answers “what is at index 2?” A map answers “what value sits under this key?” The key might be a part name, a user id, or a word. You do not walk the whole list to find it.
Include <map>. The type is map<Key, Value>. This chapter usesmap<string, int>: a string key and an integer value. StudyGrid compiles these programs as C++17.
Insert with []
stock["nails"] = 40; creates the key if it is new, or replaces the value if it already exists. Reading stock["screws"] returns that integer. If you read a missing key with [], the map inserts it with a default value (0 for int). That surprise is why the next section uses count before you treat a key as present.
Example
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> stock;
stock["nails"] = 40;
stock["screws"] = 12;
cout << stock["nails"] << endl;
cout << stock["screws"] << endl;
return 0;
}Output is 40 then 12.
Use Try it in C++ so the program opens at /cpp/try. g++ compiles it in the browser. The Python page at /try will not accept this code.
insert and count
insert adds a pair when the key is new. If the key is already there, insert leaves the old value alone. That differs from [], which overwrites. count(key) returns1 when the key exists and 0 when it does not. A map never stores two copies of the same key, so the answer is never 2.
Example
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> stock;
stock.insert({"bolts", 8});
stock.insert({"bolts", 99});
cout << stock["bolts"] << endl;
cout << stock.count("bolts") << endl;
cout << stock.count("glue") << endl;
return 0;
}Output is 8, then 1, then 0. The second insert did not replace 8 with 99. There is still no "glue" key, so count is 0.
Iterate in key order
A range-for on a map visits each pair. item.first is the key. item.second is the value. std::map keeps keys sorted, so the loop is not “insertion order.” It is sorted order of the keys.
Example
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> stock;
stock["screws"] = 12;
stock["nails"] = 40;
stock["bolts"] = 8;
for (auto item : stock) {
cout << item.first << " " << item.second << endl;
}
return 0;
}The three lines print as bolts, nails, screws — alphabetical, not the order you assigned. C++17 also lets you writefor (auto [key, value] : stock); first and second are enough here.
String keys, integer values
The pattern is the same for any key type that can be ordered. Strings are the usual choice for names. Integers work as keys too (map<int, string> for an id to a label). This listing tallies votes by candidate name.
Example
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> votes;
votes["Ada"] = 0;
votes["Linus"] = 0;
votes["Ada"] = votes["Ada"] + 1;
votes["Ada"] = votes["Ada"] + 1;
votes["Linus"] = votes["Linus"] + 1;
cout << "Ada " << votes["Ada"] << endl;
cout << "Linus " << votes["Linus"] << endl;
if (votes.count("Bjarne") == 0) {
cout << "no Bjarne" << endl;
}
return 0;
}Output is Ada 2, Linus 1, then no Bjarne.
Ordered map
std::map is an ordered map: keys stay sorted, lookup is logarithmic, and a loop is alphabetical (or numeric) by key. If you do not need that order and you want average constant-time lookup, C++ also hasunordered_map in <unordered_map>. This tutorial stays withstd::map.
| vector | map | |
|---|---|---|
| Lookup | By index, or scan with find | By key |
| Order in a loop | The order you pushed | Sorted by key |
| Duplicate keys | Allowed as duplicate values | One entry per key |
When a map is the wrong tool
If you only have a list and you always walk it from the front, keep a vector. If you need unique values with no extra payload, a set is the smaller type: just the keys. That is the next chapter.
These listings never open files. They compile with g++ in /cpp/try and on Compiler Explorer.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.
Chemistry
Atomic number by symbol
Oxygen is 8, carbon is 6. A map looks up the integer from the symbol so you do not scan a list. ["O"] is 8. Missing keys insert 0 if you use []; count() tests first in careful code.
Example
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> Z;
Z["O"] = 8;
Z["C"] = 6;
cout << "oxygen Z = " << Z["O"] << endl;
return 0;
}Astronomy
Planet year in Earth days
Mars 687, Jupiter 4333. The key is the name; the value is the sidereal period in Earth days. Lookup beats a long if/else chain when the catalogue grows.
Example
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> year = {{"Mars", 687}, {"Jupiter", 4333}};
cout << year["Mars"] << " Earth days" << endl;
return 0;
}