1、對key值進行特定的排序ios
map容器裏面有兩個值一個key一個是value,map<key,value>,其實map裏面還有第三個參數,是一個類,用來對map的key進行排序的類,定義以下app
template<class _Kty, class _Ty, class _Pr = less<_Kty>, class _Alloc = allocator<pair<const _Kty, _Ty> > > class map
less<_Kty>的代碼less
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進行的排序分別以下spa
以上就對key值進行了你想要的排序方式。3d
2、對value的值進行排序code
由於map的模板裏面沒有對value的值進行排序的參數,因此只能藉助sort函數,然而sort函數只能對vector,list,queue等排序,沒法對map排序,那麼就須要把map的值放入vector中在對vector進行排序,在對vector進行輸出,從而間接實現了對map的排序。sort也有第三個參數,跟上面那個map相似,因此能夠寫一個類或者函數來將其排序。blog
#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進行了排序,而後在將其輸出便可。ip
若是感受寫函數過於繁瑣也能夠直接在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(); }