set:
class cmp {
public:
bool operator()(const int& a,const int& b) const{
return a > b;
}
};
set<int,cmp>st;
这里用class和struct是一样的,没什么区别
注意要点:
1. 重载的符号需要是(),而不是大于>小于<号
2.需要是常函数(参数列表后加const)和常参数列表(const int& a)
map:
class cmp {
public:
bool operator()(const int& a,const int & b) const{
return a > b;
}
};
map<int, int,cmp>mp;
注意要点同上
这里可以看出,map和set的自定义比较方式是没有区别的
但有时候,我们确实也需要通过比较键值对中值的方式来排序,这样的话,是得用
set<pair<int,int>,cmp>st;
要用上面的这种方式,直接舍弃map,因为map压根没法做到根据值排序!!
此时重定义方式和上面的代码一样,不过是参数列表换成pair<int,int>,该加的const还得加