python collections.Counter 的 C++ 等价物是什么?

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

python collections.Counter 对象跟踪对象的计数。

>> 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}

是否有类似的 C++ 对象,我可以在其中轻松跟踪某个类型的出现次数?也许 mapstring?请记住,以上只是一个示例,在 C++ 中,这将推广到其他类型以进行计数。

您可以使用 std::map 如:

#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;
    }
}

输出:

1:0
cat:2
dog:8

您可以使用 std::unordered_map if you want constant on average lookup complexity (as you get using collections.Counter). std::map "usually implemented as red-black trees",因此查找的复杂度与容器大小成对数关系。而且我们在内置库Python中没有红黑树实现。

std::unordered_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;
}

Python3代码:

import collections

stringlist = ["Cat","Cat","Cat","Dog","Dog","Lizard"]
counterinstance = collections.Counter(stringlist)
for key,value in counterinstance.items():
    print(key,":",value)

C++ 代码:

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

int main()
{
   
    unordered_map <string,int> counter;
    vector<string> stringVector {"Cat","Cat","Cat","Dog","Dog","Lizard"};

    for (auto stringval: stringVector)
    {
        if (counter.find(stringval) == counter.end()) // if key is NOT present already
        {
            counter[stringval] = 1; // initialize the key with value 1
        }
        else
        {
            counter[stringval]++; // key is already present, increment the value by 1
        }
    }
    for (auto keyvaluepair : counter)
    {
        // .first to access key, .second to access value
        cout << keyvaluepair.first << ":" << keyvaluepair.second << endl; 
    }
    return 0;
}

输出:

Lizard:1
Cat:3
Dog:2

您可以使用 CppCounter:

#include <iostream>
#include "counter.hpp"

int main() {
    collection::Counter<std::string> counter;
    ++counter["cat"];
    ++counter["cat"];
    counter["dogs"] = 8;
    counter["lizards"] = 0;

    std::cout << "{ ";
    for (const auto& it: counter) {
        std::cout << "\"" << it.first << "\":" << it.second.value() << " ";

    }
    std::cout << "}" << std::endl;
}

CppCounter 是 collections.Counter: https://gitlab.com/miyamoto128/cppcounter 的 C++ 实现。 它写在 unordered_map 之上并且易于使用。

我可以补充一下我是作者 ;)