python collections.Counter的C ++等效项是什么?

时间:2018-10-30 00:01:43

标签: python c++ object counter equivalent

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 ++中,它将泛化为其他类型以供计数。

4 个答案:

答案 0 :(得分:6)

您可以使用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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您可以使用 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 的 C++ 实现:https://gitlab.com/miyamoto128/cppcounter。 它写在 unordered_map 之上,易于使用。

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

答案 3 :(得分:0)

如果要使平均查找复杂度保持恒定(使用collections.Counter时),可以使用std::unordered_mapstd::map“通常实现为红黑树”,因此查找的复杂度在容器大小上是对数的。而且我们没有内置库中使用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;
}