- 没提上司的舞会
结构体与pair的排序方法
- @ 2025-3-14 16:42:46
自己定义比较算子
可以有多种方法,最常见的就是重载比较运算符,注意重载操作返回的结果是bool类型,并且此处的比较操作与map等其他处不同,在map中以<作为比较操作,则值小的排在前面,而优先级队列中以<作为比较操作,值大的优先级高,而优先级高的放在队列前面,反之以>操作符确定优先级关系时,表明优先级是按值从大到小排列,值小的优先级高,优先级高的放在队列前面。
自定义优先级的三种方法:
1.结构体声明方式:定义在结构体内部
第一种方式:
struct node{
int x,y,z;
friend bool operator<(const node &a,const node &b){
return a.z<b.z; //按z从大到小排列
}
};
priority_queue<node>q;
第二种方式:
struct node{
int x,y,z;
bool operator<(const T &a) const {
return z<a.z; // '>'按照z从小到大排列,'<'按照z从大到小排列
}
};
下面这个例子是结构体声明方式,在priority_queue中插入若干个结构体,结构体成员为(x,y,z),以结构体成员z值来确定优先级顺序:
#include <bits/stdc++.h>
using namespace std;
struct T{
int x,y,z;
friend bool operator<(const T &a,const T &b){
return a.z<b.z; // '>'按照z从小到大排列,'<'按照z从大到小排列
}
}a;
priority_queue<T>q;
int main()
{ for(int i=1;i<=4;i++)
{ cin>>a.x>>a.y>>a.z;
q.push(a);
}
while(!q.empty())
{ T t=q.top();
q.pop();
cout<<t.x<<" "<<t.y<<" "<<t.z<<endl;
}
system("Pause");
return 1;
}
#include <bits/stdc++.h>
using namespace std;
struct T{
int x,y,z;
bool operator<(const T &a) const {
return z<a.z; // '>'按照z从小到大排列,'<'按照z从大到小排列
}
}a;
priority_queue<T>q;
int main()
{ for(int i=1;i<=4;i++)
{ cin>>a.x>>a.y>>a.z;
q.push(a);
}
while(!q.empty())
{ T t=q.top();
q.pop();
cout<<t.x<<" "<<t.y<<" "<<t.z<<endl;
}
system("Pause");
return 1;
}
2、结构体声明方式:定义在结构体外部,重载操作符
bool operator < (const node &a, const node &b) //或者写成 bool operator< (node a, node b){
return a.z < b.z; // 按照z从大到小排列
}
priority_queue<node>q;
(const node &a 是用引用传递,比按值传递 node a 效率更高,效果是一样的).
下面这个例子是重载比较运算符,在priority_queue中插入若干个结构体,结构体成员为(x,y,z),以结构体成员z值来确定优先级顺序,z值大的排在队列前面:
#include <bits/stdc++.h>
using namespace std;
struct T
{ int x,y,z;
}a;
bool operator<(const T &t1,const T &t2) //或者写成 bool operator<( const T &t1, const T &t2)
{ return t1.z<t2.z; // '>'按照z从小到大排列,'<'按照z从大到小排列
}
int main()
{ priority_queue<T>q;
for(int i=1;i<=4;i++)
{ cin>>a.x>>a.y>>a.z;
q.push(a);
}
while(!q.empty())
{ T t=q.top();
q.pop();
cout<<t.x<<" "<<t.y<<" "<<t.z<<endl;
}
system("Pause");
return 1;
}
3.比较函数声明方式:
struct cmp{
bool operator ()( node &a, node &b)//或者写成 bool operator<(const node &a, const node )
{
return a.value>b.value;// 按照value从小到大排列
}
};
priority_queue<node, vector<node>, cmp>q;
下面这个例子是自定义比较函数,在priority_queue中插入若干个结构体,结构体成员为(x,y,z),以结构体成员z值来确定优先级顺序:
#include <bits/stdc++.h>
using namespace std;
struct T
{ int x,y,z;
}a;
struct cmp
{ bool operator ()(T &a, T &b) //或者写成 bool operator ()(const T &a,const T &b)
{ return a.z>b.z;// '>'按照z从小到大排列,'<'按照z从大到小排列
}
};
priority_queue<T, vector<T>, cmp>q;
int main()
{ for(int i=1;i<=4;i++)
{ cin>>a.x>>a.y>>a.z;
q.push(a);
}
while(!q.empty())
{ T t=q.top();
q.pop();
cout<<t.x<<" "<<t.y<<" "<<t.z<<endl;
}
system("Pause");
return 1;
}
0 条评论
目前还没有评论...
信息
- ID
- 81
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 6
- 标签
- (无)
- 递交数
- 45
- 已通过
- 14
- 上传者