Search code examples
pythonc++objectcounterequivalent

What is the C++ equivalent of python collections.Counter?


The python collections.Counter object keeps track of the counts of objects.

>> from collections import Counter
>> myC = Counter()
>> myC.update("cat")
>> myC.update("cat")
>> myC["dogs"] = 8
>> myC["lizards"] = 0
>> print(myC)
{"cat": 2, "dogs": 8, "lizards": 0}

Is there an analogous C++ object where I can easily keep track of the occurrence counts of a type? Maybe a map to string? Keep in mind that the above is just an example, and in C++ this would generalize to other types to count.


Solution

  • You could use an std::map like:

    #include <iostream>
    #include <map>
    
    int main()
    {
        std::map<std::string,int> counter;
        counter["dog"] = 8;
        counter["cat"]++;
        counter["cat"]++;
        counter["1"] = 0;
    
        for (auto pair : counter) {
            cout << pair.first << ":" << pair.second << std::endl;
        }
    }
    

    Output:

    1:0
    cat:2
    dog:8