c++ 統計 vector 每個元素出現的次數 (C++ count the number of occurrences of each element in vector)


 

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 }

 

結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM