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
m.find(key)returns an iterator to the entry, orm.end()if the key isn't there. Always compare withend()before using the result.- The iterator points at a pair:
it->firstis the key,it->secondis the value. m.contains(key)(C++20) just answers yes or no. Use it when you don't need the value.m.count(key)returns 0 or 1 for a map and works in older C++ too.
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
- Using
it->secondwithout checkingit != m.end(). Dereferencingend()is undefined behavior. - Using
m[key]in anifto test whether something exists. The test itself creates the entry.
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.)