这里只讲常用的两种方式(以优先队列和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;
}