为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕标5832272 2021-07-30 17:04:29
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++ 中,这将推广到其他类型以进行计数。
查看完整描述

3 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

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


查看完整回答
反对 回复 2021-08-03
  • 3 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信