Map lookup in C++
std::map keeps keys sorted and gives you three ways in: subscript, contains, and find.
#include <map>
#include <string>
int ages_demo() {
std::map<std::string, int> ages = {{"ada", 36}, {"alan", 41}};
ages["grace"] = 85; // subscript inserts the key
if (ages.contains("alan")) {
ages.erase("alan");
}
auto it = ages.find("ada");
return it != ages.end() ? it->second : 0;
}
How it works
- Brace pairs seed the map;
ages["grace"] = 85inserts a key that was not there. - C++20's
containsasks the yes-or-no question without creating anything. findreturns an iterator:it->secondis the value,end()means the key is absent.
Keywords and builtins used here
ages_demoautoifintreturn
The run, in numbers
- Lines
- 12
- Characters to type
- 300
- Tokens
- 105
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 90 seconds.
Step 2 of 3 in Containers, step 8 of 27 in Language basics.