How can I count the number of repeated elements/value in map?

Here is a simple solution:

#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <unordered_map>

using namespace std;



int main() {

    unordered_map<int, size_t> counts;


    std::map<std::string, int> m = { 
        {"XzbitYmay",  64},  
        {"Bruce Watson",  53}, 
        {"Nim George",  53},
        {"Lee Harry",  64},
        {"Nim George",  59 }};

    for(const auto& kvp : m) {
        counts[kvp.second]++;
    }

    for(const auto& kvp: counts) {
        if(kvp.second > 0)
            std::cout << kvp.first << "->" << kvp.second << '\n';
    }

    return 0;
}

Live example here.

Browse More Popular Posts

Leave a Comment