猿问

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

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++ 对象可以轻松跟踪类型的出现次数?也许一个map到string?请记住,以上只是一个示例,在 C++ 中,这将推广到其他类型以进行计数。


慕标5832272
浏览 184回答 3
3回答

慕姐4208626

Python3代码:import collectionsstringlist = ["Cat","Cat","Cat","Dog","Dog","Lizard"]counterinstance = collections.Counter(stringlist)for key,value in counterinstance.items():&nbsp; &nbsp; print(key,":",value)C++代码:#include <iostream>#include <unordered_map>#include <vector>using namespace std;int main(){&nbsp; &nbsp;&nbsp; &nbsp; unordered_map <string,int> counter;&nbsp; &nbsp; vector<string> stringVector {"Cat","Cat","Cat","Dog","Dog","Lizard"};&nbsp; &nbsp; for (auto stringval: stringVector)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (counter.find(stringval) == counter.end()) // if key is NOT present already&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter[stringval] = 1; // initialize the key with value 1&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter[stringval]++; // key is already present, increment the value by 1&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for (auto keyvaluepair : counter)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // .first to access key, .second to access value&nbsp; &nbsp; &nbsp; &nbsp; cout << keyvaluepair.first << ":" << keyvaluepair.second << endl;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; return 0;}输出:Lizard:1Cat:3Dog:2
随时随地看视频慕课网APP

相关分类

Python
我要回答