比如对于"100","99"要进行排序
set<string> myset={"99","100"};
//set的三种遍历方式
for(string s:myset) cout<<s<<' ';
for(const string& s:myset) cout<<s<<' ';//set的值本身是不可修改的,使用引用就要加上const
for(auto it=myset.begin();it!=myset.end();it++) cout<<*it<<' ';
可以发现,上述输出为"100",“99”,因为默认采用的less,按照字典序的从小到大,因为1比9小,所以1放前,如果要实现"99"放“100”前面,那么就要自定义比较函数了
注意要声明为const成员函数
值传递
struct cmp{
bool operator()(string a,string b)const{
return stoi(a)<stoi(b);
}
};
set<string,cmp> myset={"99","100"};
class cmp{
public:
bool operator()(string a,string b)const{
return stoi(a)<stoi(b);
}
};
set<string,cmp> myset={"99","100"};
引用传递
struct cmp{
bool operator()(const string& a,const string& b)const{
return stoi(a)<stoi(b);
}
};
set<string,cmp> myset={"99","100"};
class cmp{
public:
bool operator()(const string& a,const string& b)const{
return stoi(a)<stoi(b);
}
};
set<string,cmp> myset={"99","100"};
后面的例子中,统一用引用传递了,不再重复了
bool cmp(const string& a,const string& b){
return stoi(a)<stoi(b);
}
int main(){
set<string,decltype(&cmp)> myset(cmp);
myset={"100","99"};
}
类成员函数要加上static
class Solution{
public:
static bool cmp(const string& a,const string& b){
return stoi(a)<stoi(b);
}
void test(){
set<string,decltype(&cmp)> myset(cmp);
myset={"100","99"};
}
};
auto cmp=[](const string& a,const string& b){
return stoi(a)<stoi(b);
};
set<string,decltype(cmp)> myset(cmp);
myset={"100","99"};
以lambda表达式的写法为例, 说明只需要修改set为multiset,其他都是一摸一样的
auto cmp=[](const string& a,const string& b){
return stoi(a)<stoi(b);
};
multiset<string,decltype(cmp)> myset(cmp);
myset={"100","99","100"};
仿函数 重载运算符()
struct cmp{
bool operator()(const string& a,const string& b)const{
return stoi(a)<stoi(b);
}
};
map<string,int,cmp> mp;
mp={{"100",1},{"99",2}};
lambda表达式
auto cmp=[](const string& a,const string& b){
return stoi(a)<stoi(b);
};
map<string,int,decltype(cmp)> mp(cmp);
mp={{"100",1},{"99",2}};
struct cmp{
bool operator()(const string& a,const string& b)const{
return stoi(a)<stoi(b);
}
};
multimap<string,int,cmp> mp;
mp={{"100",1},{"99",2}};
都是一个套路,记住了set的自定义排序方法
也就等于会了set、multiset、map、multimap的自定义排序