一、對key值進行特定的排序
map容器里面有兩個值一個key一個是value,map<key,value>,其實map里面還有第三個參數,是一個類,用來對map的key進行排序的類,定義如下
template<class _Kty, class _Ty, class _Pr = less<_Kty>, class _Alloc = allocator<pair<const _Kty, _Ty> > > class map
less<_Kty>的代碼
struct less : public binary_function<_Ty, _Ty, bool> { // functor for operator< bool operator()(const _Ty& _Left, const _Ty& _Right) const { // apply operator< to operands return (_Left < _Right); } };
那么根據上面的代碼我們也可以寫出一個greater類來讓key按照降序排列
#include <iostream> #include <string> #include <map> using namespace std; typedef pair<string, int> PAIR; struct greater { bool operator()(const string& _Left, const string& _Right) const { return (_Left > _Right); } }; int main() { map<string, int,greater> ma; ma["Alice"] = 86; ma["Bob"] = 78; ma["Zip"] = 92; ma["Stdevn"] = 88; for (map<string, int>::iterator ite = ma.begin(); ite != ma.end(); ++ite) { cout << ite->first << " " << ite->second << endl; } getchar(); }
默認的排序和用greater進行的排序分別如下
以上就對key值進行了你想要的排序方式。
二、對value的值進行排序
因為map的模板里面沒有對value的值進行排序的參數,所以只能借助sort函數,然而sort函數只能對vector,list,queue等排序,無法對map排序,那么就需要把map的值放入vector中在對vector進行排序,在對vector進行輸出,從而間接實現了對map的排序。sort也有第三個參數,跟上面那個map類似,所以可以寫一個類或者函數來將其排序。
#include <iostream> #include <string> #include <map> #include <algorithm> #include <vector> using namespace std; typedef pair<string, int> PAIR; bool cmp_val(const PAIR &left,const PAIR &right) { return left.second < right.second; } int main() { map<string, int> ma; ma["Alice"] = 86; ma["Bob"] = 78; ma["Zip"] = 92; ma["Stdevn"] = 88; vector<PAIR> vec(ma.begin(),ma.end()); sort(vec.begin(),vec.end(),cmp_val); for (vector<PAIR>::iterator ite = vec.begin(); ite != vec.end(); ++ite) { cout << ite->first << " " << ite->second << endl; } getchar(); }
結果如下
這樣就通過cmp_val函數對vector進行了排序,然后在將其輸出即可。
如果感覺寫函數過於繁瑣也可以直接在sort里面用lambda表達式,代碼如下
#include <iostream> #include <string> #include <map> #include <algorithm> #include <vector> using namespace std; typedef pair<string, int> PAIR; int main() { map<string, int> ma; ma["Alice"] = 86; ma["Bob"] = 78; ma["Zip"] = 92; ma["Stdevn"] = 88; vector<PAIR> vec(ma.begin(),ma.end()); sort(vec.begin(), vec.end(),[](const PAIR &left, const PAIR &right) { return left.second < right.second; }); for (vector<PAIR>::iterator ite = vec.begin(); ite != vec.end(); ++ite) { cout << ite->first << " " << ite->second << endl; } getchar(); }