typestar

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

  1. Brace pairs seed the map; ages["grace"] = 85 inserts a key that was not there.
  2. C++20's contains asks the yes-or-no question without creating anything.
  3. find returns an iterator: it->second is the value, end() means the key is absent.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Containers, step 8 of 27 in Language basics.

← Previous Next →

Map lookup in other languages