Codiqo

Learn C++ · lesson 32 of 61 · about 8 minutes

Counting with Maps

Count the monsters met in the castle with a map, and find the one met most.

What you'll learn

  • Count with m[key]++
  • Find the largest count
  • Use unordered_map when order doesn't matter

Monsters met

The castle isn't empty: bats, ghosts and worse jump out as the hero goes. Each monster's name is typed until done, and the adventure counts them in a std::map<std::string, int>. Because met[monster] starts a monster it hasn't seen at 0, counting is one line, met[monster]++. Then one loop prints each monster's count and finds the one met most.

The counting pattern

Because m[key] starts a missing key at 0, counting is one line: counts[word]++;

To find the most common, loop over the map and keep the pair with the biggest count.

std::unordered_map works the same way and is usually faster, but its order is unpredictable. Use std::map when you want sorted output.

Counting votes

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

int main() {
    std::map<std::string, int> votes;
    for (std::string v : {"py", "js", "py", "c", "py", "js"}) votes[v]++;
    std::string winner;
    int best = 0;
    for (const auto& [lang, n] : votes) {
        std::cout << lang << " " << n << "\n";
        if (n > best) {
            best = n;
            winner = lang;
        }
    }
    std::cout << "Winner: " << winner << "\n";
}

Output

c 1
js 2
py 3
Winner: py

Tip

Counting characters works the same way with std::map<char, int>.

Now try it yourself

This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.