我有一个 priority_queue
结构指针,我想获得一些“val”值最小的“事件”节点。这是我发现的,但它不关心节点的事件,只给出值最小的元素。
#include<bits/stdc++.h>
using namespace std;
struct node{
long long val;
bool active;
};
struct Compare
{
bool operator()(const node *a,const node *b)const
{
if(a->active == b->active)
return (a->val) > (b->val);
if(a->active)
return 1;
return 0;
}
};
typedef priority_queue<node*, vector<node*> ,Compare > PQ;
int main()
{
PQ q;
int n;
cin >> n;
for(int i=1;i<=n;i++)
{
int x;
cin >> x;
node* nd=new node;
nd->val = x;
nd->active = 1;
q.push(nd);
}
node* first =q.top();
cout << "the top element is " << (first->val) << endl;
q.pop();
first->active = 0;
q.push(first);
node* second = q.top();
cout << "the next top element is " << (second->val) << endl;
cout << "the activity state of the second element is " << (second->active) << endl;
return 0;
}
更新:代码现在可以工作并且确实关心节点的事件
最佳答案
priority_queue
中的元素在添加后无法修改。如果要执行此操作,您需要关闭 pop
值,对其进行修改,然后将其push
重新打开。
关于c++ - 用于结构指针的 priority_queue 的自定义比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029241/