对c++中的map结构进行排序

map是key有序的结构,自动实现key的顺序和去重;
如果相对value排序,要自己定义pair结构。

#include <map>
#include <string>
#include <iostream>
using namespace std;
// 自己编写的Compare,实现按照字符串长度进行排序
struct CmpByKeyLength {  
  bool operator()(const string& k1, const string& k2) {  
    return k1.length() < k2.length();  
  }  
};  
int main(){
    map<string, int, CmpByKeyLength > mapStudent;  //这里注意要换成自己定义的compare
    mapStudent["LiMin"]=90;
    mapStudent["ZiLinMi"]=72;
    mapStudent["BoB"]=79;
    map<string, int>::iterator iter=mapStudent.begin();
    for(iter=mapStudent.begin();iter!=mapStudent.end();iter++){
        cout<<iter->first<<" "<<iter->second<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PETERPARKERRR/article/details/122831714