Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Missing Keys

What happens when you read a key that isn't in the map? With a vector, an index past the end gives you a meaningless number. A map does something else: square brackets add the missing key with the value 0, and give you that 0:

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

int main() {
    std::map<std::string, int> inventory = {
        {"bread", 2},
        {"potion", 3}
    };

    std::cout << "Potions: " << inventory["poiton"] << std::endl;
    std::cout << "Different items: " << inventory.size() << std::endl;
    return 0;
}

This prints:

Potions: 0
Different items: 3

A typo in a key isn't an error. The program runs, says that Aria has no potions, and her inventory now has a third item, "poiton". Uppercase and lowercase letters matter as well: "Potion" and "potion" are two different keys. Adding a missing key with 0 is handy when you count, as you will in the next exercise. But when you only want to look, it's a trap.

Two methods look without adding anything. count(key) tells you whether the key is in the map: it gives 1 when it is, and 0 when it isn't. Keys are unique, so it's never more than 1:

if (inventory.count("helmet") == 0) {
    std::cout << "No helmet" << std::endl;
}

at(key) reads a value like square brackets do. But when the key is missing, it stops the program, just as at() does with an index outside a vector:

std::cout << "Potions: " << inventory.at("potion") << std::endl;
std::cout << "Helmets: " << inventory.at("helmet") << std::endl;
std::cout << "End" << std::endl;

This prints Potions: 3, and then the program stops with an error:

std::out_of_range: map::at:  key not found
RuntimeError: unreachable

The first line says that a key wasn't found. End is never printed.

So which one do you use? Square brackets when you add or change a value, or when 0 is the right answer for a missing key. count() when you want to ask first. And at() when the key must be there: if it isn't, your program has a bug, and it's better to stop right away than to go on with a 0. Newer versions of C++ also have contains(key), which you will see online, but the compiler here uses C++17, which doesn't have it yet: no member named 'contains' in 'std::map<std::string, int>'.

Instructions

  1. 1

    Aria goes shopping with a list. Run the program: it says that a sword costs 0, and the shop suddenly has 4 items, because the square brackets added the sword to the map. Change the loop so that for an item the shop doesn't have, it prints sword: not in the shop (with the item's name) and adds nothing. Use count(). The program prints:

    potion: 15
    sword: not in the shop
    bread: 3
    Items in the shop: 3

    Keep the line with shoppingList as it is: the exercise will also try another list.

  2. 2

    Add up the prices of the items Aria can buy, and print the total on the last line: Total: 18. You know that these items are in the map, so you can read their prices with at().

Back

4/12

  1. 1. What Is a Map?
  2. 2. Adding and Changing Values
  3. 3. Looping over a Map
  4. 4. Missing Keys
  5. 5. Counting with a Map
  6. 6. Quiz: Counting Loot
  7. 7. Removing Elements
  8. 8. Maps and Functions
  9. 9. Quiz: Restocking
  10. 10. Structs as Values
  11. 11. Unordered Maps
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.