C/C++ Arena

Step 2 of 6

Look up without inserting

There's a trap in m[key]: it inserts the key when it's missing. If you only wanted to check a price, you've just added a bogus item with price 0. For a pure lookup, use find or contains.

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, std::string> capital = {{"France", "Paris"}, {"Japan", "Tokyo"}};

    auto it = capital.find("Japan");
    if (it != capital.end()) {
        std::cout << it->first << " -> " << it->second << "\n";
    }
    if (!capital.contains("Peru")) {
        std::cout << "no entry for Peru\n";
    }
    std::cout << capital.size() << " entries\n";

    std::string oops = capital["Chile"];    // inserts "Chile" with an empty string
    std::cout << capital.size() << " entries after using []\n";
}
Japan -> Tokyo
no entry for Peru
2 entries
3 entries after using []

How it works

Why const matters here

When a function takes const std::map<...>&, it promises not to change the map. Since [] might insert, the compiler won't let you call it on a const map. That's a helpful error: it forces you to use find.

Common mistakes

Your turn: write int price_of(const std::map<std::string, int>& prices, const std::string& item) that returns the price, or -1 if the item isn't in the map. (The map is const, so [] isn't even allowed.)

Previous: std::map Next: std::set