Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 724
conchoecia Avatar asked Oct 30 '18 00:10

conchoecia


People also ask

What is counter in python collection?

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.

Is there a counter in Python?

Python CounterCounter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers. However there is no restriction on it's keys and values.

How do you call a counter in Python?

Counter supports three forms of initialization. Its constructor can be called with a sequence of items, a dictionary containing keys and counts, or using keyword arguments mapping string names to counts. To create an empty counter, pass the counter with no argument and populate it via the update method.

What does counter return in Python?

Python Counter is a subclass of the dict or dictionary class . It keeps track of the frequency of each element in the container . It takes as argument an iterable object (like list) and returns back a dictionary.


1 Answers

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
like image 191
Stephan Lechner Avatar answered Sep 24 '22 19:09

Stephan Lechner