注意:都是传递的类,而非仿函数。
set自定义排序
- 内置数据类型
#include <bits/stdc++.h>
using namespace std;
class MyCompare {
public:
bool operator()(int a, int b){
return a > b;
}
};
int main(){
set<int, MyCompare> st;
st.insert(10);
st.insert(40);
st.insert(30);
st.insert(20);
st.insert(50);
//默认升序 从小到大
//自定义实现降序 从大到小
for(auto it: st){
cout<<it<<endl;
}
return 0;
}
- 复杂数据类型【重点】
#include <bits/stdc++.h>
using namespace std;
//自定义类
class Student{
public:
string name;
int age;
Student(const string &name, int age) : name(name), age(age) {
}
};
//二元谓词仿函数
class MyCompare {
public:
bool operator()(Student a, Student b){
if (a.age != b.age) return a.age < b.age;
return a.name < b.name;
}
};
int main(){
//重点
set<Student, MyCompare> st;
st.insert({
"Jack", 18});
st.insert(