重定义容器排序方式

这里只讲常用的两种方式(以优先队列和set作为示例):

1.在结构体内重载“<”运算符

#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x,y,step;
	bool operator < (const node A) const//重载< 
	{
		return A.step < step;//按step从大到小排序 
	}
};
int main()
{
	set<node> s;
	node t;
	t.x = 99; t.y = 99; t.step = 1;
	s.insert(t);
	t.x = 70; t.y = 60; t.step = 3;
	s.insert(t);
	t.x = 999; t.y = 999; t.step = 2;
	s.insert(t);
	t.x = 99; t.y = 99; t.step = 4;
	s.insert(t);
	
	for(set<node>::iterator it = s.begin(); it != s.end(); it++)
	{
		printf("%d %d %d\n",(*it).x,(*it).y,(*it).step);
	}
	return 0;
}

2.重载“()”运算符

#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x,y,step;
};
//重载括号 
struct cmp1
{
    bool operator () (const node &a,const node &b) const
	{  
        return a.step < b.step;//按step从大到小排序  
    }  
};
int main()
{
	priority_queue<node,vector<node>,cmp1> pq;
	node t;
	t.x = 99; t.y = 99; t.step = 1;
	pq.push(t);
	t.x = 70; t.y = 60; t.step = 3;
	pq.push(t);
	t.x = 999; t.y = 999; t.step = 2;
	pq.push(t);
	t.x = 99; t.y = 99; t.step = 4;
	pq.push(t);
	
	while(!pq.empty())  
    {  
        cout << (pq.top()).x << " " << (pq.top()).y << " " << (pq.top()).step << endl;  
        pq.pop();  
    }   
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值