Counting with a Map

The counting pattern

m[key] creates the key with value 0 the first time you use it, so counting is one line:

#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> votes = {"tea", "coffee", "tea", "juice", "tea", "coffee"};
    map<string, int> count;               // map: printed in sorted order
    for (const string& v : votes) count[v]++;
    for (auto& [drink, n] : count) cout << drink << ": " << n << endl;
    return 0;
}

Output

coffee: 2
juice: 1
tea: 3

auto& [drink, n] unpacks each key/value pair (a C++17 feature called structured bindings).

Anagrams

Two words are anagrams if they use exactly the same letters (listen / silent). For lowercase letters, an array of 26 counters is the fastest “map”:

#include <iostream>
#include <string>
using namespace std;

bool isAnagram(const string& a, const string& b) {
    if (a.size() != b.size()) return false;
    int count[26] = {0};
    for (char c : a) count[c - 'a']++;
    for (char c : b) count[c - 'a']--;
    for (int x : count)
        if (x != 0) return false;
    return true;
}

int main() {
    cout << isAnagram("listen", "silent") << " " << isAnagram("apple", "paper") << endl;
    return 0;
}

Output

1 0

Tip: c - 'a' turns a lowercase letter into 0 … 25, a perfect array index.

HOME LABS COMMUNITY DASHBOARD