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 task
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.)
Challenge 2
Write bool buy(std::map<std::string, int>& stock, const std::string& item). If the item is in stock (count above 0), take one and return true, removing the item from the map when its count reaches 0. Otherwise return false, and don't add anything to the map.
Challenge 3
Write std::map<char, int> letter_counts(const std::string& s) that counts only the lowercase letters a to z, ignoring everything else. Letters that don't appear must not be in the map at all.