【合集】自定义结构体 vector & priority_queue & set & map 的构建一网打尽!(C++干货)

 结构体 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一定是根据键来排序的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值