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 }
结果如下: