结构体 vector 的 sort 排序实现
struct Node{
int a, b;
bool operator<(const Node& other)const{
return a < other.a;//升序:从小到大
//return a < other.a;//降序:从大到小
}
};
vector<Node>vc;
sort(vc.begin(), vc.end());
结构体 set 构建
struct Node{
int x;
int y;
bool operator<(const Node& other) const{
if(x == other.x) return y < other.y;
else return x < other.x;
}
};
set<Node>st;
Node t_node;
st.insert(t_node);
//只有t_node的x,y值与set中已有元素完全相等时,才不会被插入
结构体 priority_queue 的构建
struct Node{
int x;
int y;
bool operator<(const Node& other)const{
//首先按x值来排序
if(x != other.x) return x < other.x;
//如果x值相等再比较y
else return y < other.y;
}
};
priority_queue<Node>pq;
结构体 map 的构建(键是自定义结构体)
struct MyKey {
int x;
int y;
bool operator<(const MyKey& other) const {
if (x == other.x) {
return y < other.y; // 若 x 相同,则比较 y
}
return x < other.x; // 否则比较 x
}
};
map<MyKey, string> myMap; //map一定是根据键来排序的