c++ 统计 vector 每个元素出现的次数 (C++ count the number of occurrences

 

c++ 统计 vector 每个元素出现的次数  (C++ count the number of occurrences of each element in vector)

参考: https://stackoverflow.com/questions/1204313/counting-occurrences-in-a-vector

 

 1 vector<int> blockType = { 2, 3, 4, 5, 2, 2, 1, 1, 5 };
 2 typedef map<int, int> mapIntInt;
 3 mapIntInt mapCount;
 4 for (int i = 0; i < blockType.size(); ++i) {
 5     mapIntInt::iterator iterator(mapCount.find(blockType[i]));
 6     if (iterator != mapCount.end()) {
 7         iterator->second++;
 8     }
 9     else {
10         mapCount[blockType[i]] = 1;
11     }
12 }
13 
14 //两种遍历map的方法
15 for_each(mapCount.begin(), mapCount.end(), [&](pair<int, int> element) {
16     int typeName = element.first;
17     int typeNumber = element.second;
18     cout << typeName << " : " << typeNumber << endl;
19     });
20 
21 cout << "--------------------------------" << endl;
22 
23 for (auto const& element : mapCount)
24 {
25     int typeName = element.first;
26     int typeNumber = element.second;
27     cout << typeName << " : " << typeNumber << endl;
28 }

 

结果如下:

c++ 统计 vector 每个元素出现的次数 (C++ count the number of occurrences

 

原文链接: https://www.cnblogs.com/ttweixiao-IT-program/p/12487064.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++ 统计 vector 每个元素出现的次数 (C++ count the number of occurrences

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/335050

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午9:57
下一篇 2023年3月1日 下午9:57

相关推荐