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

Counting with a Map

That square brackets add a missing key with 0 makes counting easy. Say the monsters in the arena dropped this loot, and you want to know how many of each thing there are:

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

int main() {
    std::vector<std::string> loot = {"gem", "potion", "gem", "bread", "gem", "potion"};

    std::map<std::string, int> counts;
    for (const std::string& item : loot) {
        counts[item]++;
    }

    for (const auto& [item, count] : counts) {
        std::cout << item << ": " << count << std::endl;
    }
    return 0;
}

This prints:

bread: 1
gem: 3
potion: 2

The first time the loop meets "gem", the key isn't in counts yet. counts["gem"] adds it with 0, and ++ makes it 1. The next time, ++ turns the 1 into 2, and so on. The other things are counted the same way, each under its own key.

In the Loops lesson, you counted with a variable of your own, count++ inside an if. That works when you know beforehand what you count. For ten kinds of loot, you would need ten variables and ten conditions, and for a kind you didn't think of, nothing would count it. The map makes a new counter for every new key by itself, and the one line counts[item]++; counts them all.

When the loop over counts prints the result, the things come out sorted, whatever order they were found in.

Instructions

  1. 1

    Count how many monsters of each kind Aria defeated: create a map counts and count the names in defeated, as in the example. Then print each monster with its number, one line each:

    Orc: 2
    Slime: 3
    Troll: 1

    Keep the line with defeated as it is: the exercise will also try other fights.

  2. 2

    Below, print the monster Aria defeated most often, with its number: Most often: Slime (3). Look for it the way you looked for the largest value in the Loops lesson: go through the map, and keep the name and the number of the best monster so far.

Back

5/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.