那么我們如何實現對pair按value進行比較呢? 第一種:是最原始的方法,寫一個比較函數; 第二種:剛才用到了,寫一個函數對象。這兩種方式實現起來都比較簡單。
- typedef pair<string, int> PAIR;
- bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) {
- return lhs.second < rhs.second;
- }
- struct CmpByValue {
- bool operator()(const PAIR& lhs, const PAIR& rhs) {
- return lhs.second < rhs.second;
- }
- };
接下來,我們看下sort算法,是不是也像map一樣,可以讓我們自己指定元素間如何進行比較呢?
- template <class RandomAccessIterator>
- void sort ( RandomAccessIterator first, RandomAccessIterator last );
- template <class RandomAccessIterator, class Compare>
- void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
我們看到,令人興奮的是,sort算法和map一樣,也可以讓我們指定元素間如何進行比較,即指定Compare。需要注意的是,map是在定義時指定的,所以傳參的時候直接傳入函數對象的類名,就像指定key和value時指定的類型名一樣;sort算法是在調用時指定的,需要傳入一個對象,當然這個也簡單,類名()就會調用構造函數生成對象。
這里也可以傳入一個函數指針,就是把上面說的第一種方法的函數名傳過來。(應該是存在函數指針到函數對象的轉換,或者兩者調用形式上是一致的,具體確切原因還不明白,希望知道的朋友給講下,先謝謝了。)
【參考代碼】
- int main() {
- map<string, int> name_score_map;
- name_score_map["LiMin"] = 90;
- name_score_map["ZiLinMi"] = 79;
- name_score_map["BoB"] = 92;
- name_score_map.insert(make_pair("Bing",99));
- name_score_map.insert(make_pair("Albert",86));
- //把map中元素轉存到vector中
- vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());
- sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());
- // sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value);
- for (int i = 0; i != name_score_vec.size(); ++i) {
- cout << name_score_vec[i] << endl;
- }
- return 0;
- }
【運行結果】
- #include <iostream>
- #include <cstdlib>
- #include <map>
- #include <vector>
- #include <string>
- #include <algorithm>
- using namespace std;
- int cmp(const pair<string, int>& x, const pair<string, int>& y)
- {
- return x.second > y.second;
- }
- void sortMapByValue(map<string, int>& tMap,vector<pair<string, int> >& tVector)
- {
- for (map<string, int>::iterator curr = tMap.begin(); curr != tMap.end(); curr++)
- tVector.push_back(make_pair(curr->first, curr->second));
- sort(tVector.begin(), tVector.end(), cmp);
- }
- int main()
- {
- map<string, int> tMap;
- string word;
- while (cin >> word)
- {
- pair<map<string,int>::iterator,bool> ret = tMap.insert(make_pair(word, 1));
- if (!ret.second)
- ++ret.first->second;
- }
- vector<pair<string,int>> tVector;
- sortMapByValue(tMap,tVector);
- for(int i=0;i<tVector.size();i++)
- cout<<tVector[i].first<<": "<<tVector[i].second<<endl;
- system("pause");
- return 0;
- }