c++ - 用于结构指针的 priority_queue 的自定义比较函数

标签 c++ struct priority-queue

我有一个 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/

相关文章:

c# - 必须使用 C++ dll 来调用 C# .NET 方法吗?

带有 wxWidgets 的 C++,Unicode 与 ASCII,有什么区别?

c++ - 将字节数组转换为结构指针取决于字节序或内存对齐方式?

c++ - 访问 boost::unordered_multimap 或结构时很少出现段错误

java - 具有优先级阻塞队列的 ThreadPoolExecutor 不会创建(动态)非核心线程

python - 如何通过python从GDB中的内存地址获取对象

c++ - 这个小c++代码背后的逻辑是什么?

C CUDA 从设备向主机发送结构数组

当我插入元素时,C++ 优先级队列崩溃

c++ - 使用自定义比较器返回priority_queue