priority_queue 自定义比较函数
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdio>
using namespace std;
struct Node{
int x;
int y;
Node(int a=0, int b=0)
{
x = a;
y = b;
}
};
struct cmp{
bool operator () (Node a, Node b)
{
if(a.x == b.x) return a.y > b.y;
else return a.x < b.x ;
}
};
/*
struct cmp{
bool operator() ( Node a, Node b )
{
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}
};*/
int main()
{
priority_queue <Node, vector<Node>, cmp > q;
for(int i= 0; i< 10; ++i )
{
q.push(Node(i,10-i));
}
while( !q.empty())
{
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
}
return 0;
}
本文介绍了一种在C++中使用自定义比较函数对priority_queue进行操作的方法。通过定义一个比较结构体cmp,我们可以改变优先队列中元素的排序规则。示例代码展示了如何创建一个包含Node结构体的优先队列,并根据Node的x和y字段值进行排序。
4万+

被折叠的 条评论
为什么被折叠?



