将元素插入map和set中时,容器会根据设定的比较函数将该元素放到相应节点上,在定义容器时,如果没有指定比较函数,那么采用默认的比较函数,及按照键值由小到大的顺序插入元素,很多情况下,需要自己编写比较函数,
map和set内部的数据结构都是红黑树,所以比较函数是一致的,编写方法有两种:
(1)如果元素不是结构体,那么可以编写比较函数,下面程序编写的比较规则是按照键值由大到小顺序插入map:
#include<iostream>
#include<map>
using namespace std;
struct myComp{
bool operator() (const int &a,const int &b){
if(a!=b) return a>b;
else return a>b;
}
};
int main(){
map<int,char,myComp> m;
m[12] = 'm';
m[1] = 'd';
m[21] = 'f';
m[32] = 'a';
map<int,char,myComp>::iterator it;
for(it = m.begin();it!=m.end();it++){
cout<<(*it).first<<":"<<(*it).second<<endl;
}
return 0;
}
#include<iostream>
#include<map>
#include<string>
#include<set>
using namespace std;
struct Info{
string name;
float score;
Info(string a,float b):name(a),score(b){}
bool operator < (const Info &a) const { //结构体内比较
return a.score<score;
}
};
struct myComp{ //自定义比较
bool operator() (const Info &a,const Info &b){
if(a.score!=b.score) return a.score>b.score;
else return a.score>b.score;
}
};
int main(){
Info a("a",99),b("b",98),c("c",65),d("d",78);
set<Info> s;
s.insert(a);
s.insert(b);
s.insert(c);
s.insert(d);
set<Info>::iterator it;
for(it = s.begin();it!=s.end();it++){
cout<<(*it).name <<":"<<(*it).score<<endl;
}
return 0;
}