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(); }