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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With