C++技巧之STL(持續更新)
一、STL——map
1.在map中按值進行排序
C++的map,是一種key-value對照的容器,在用sort進行排序時,如果不進行變換是不能直接對值(value),因爲sort排序,只能對順序容器排序,所以只能對map的key,也就是關鍵字,排序。而大多數時候,需要對map的value,進行排序,比如,用map表示分數和人數 map<int, int> 需要輸出人數最多或者最少的人對應的分數,或者按人數遞增,遞減的順序輸出對應的成績。就需要就行轉換了。可以將map放在vector中,然後對vector 進行排序,在直接操作!
代碼如下:
bool cmp(const pair<int, int>& x, const pair<int, int>& y) { return x.second < y.second; } int main() { map<int, int>m; for (int i = 0; i < 10; ++i) { cin >> tmp; m[tmp]++; } vector< pair<int, int> >n(m.begin(), m.end()); //用> > 不用>> 是因爲>>是cout裏面的,帶有運算符重載 sort(n.begin(), n.end(), cmp); cout << n[0].first << endl; return 0; } //輸入80 90 90 80 90 80 70 60 60 60 //map中key-value爲 //80---->3 //90---->3 //70---->1 //60---->3 //排序後70---->1這組在容器第一位,所以輸出70