python集合的C++等价物是什么.计数器

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

本文关键字:是什么 计数器 等价物 C++ 集合 python      更新时间:2023-10-16

pythoncollections.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

如果您想要恒定的平均查找复杂度(就像使用collections.Counter一样(,可以使用std::unordered_map。std::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;
}

您可以使用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是集合的C++实现。计数器:https://gitlab.com/miyamoto128/cppcounter.它是在undered_map之上编写的,易于使用。

我可以补充一下,我是作者;(

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