简体   繁体   中英

Modified comparator for priority_queue of C++ not working properly

In the code given below, I am trying to keep some values in priority_queue sorted accordingly their key values, which are stored in the "key" vector. And then, I am changing the key values to see if the comparator working properly or not. Here, when I change the key[8] to 10, value 8 changes its position in the queue correctly. But when I changed the key[2] to -1, it changed it's position in the queue, but not correctly. It should be positioned at the top of the queue, as it's key value is the smallest, but it's not.

Is my way of writing the code of the comparator wrong? Or, It's something else that I am not doing correctly?

I want to know the correct way to modify the comparator of priority queue if I want to sort values in ascending order accordingly to their key values.

在此处输入图片说明

#include <bits/stdc++.h>
using namespace std;
vector <int> key(1000);
struct comp{
    bool operator()(int a,int b)const{
        return key[a]>key[b];
    }
};
int main()
{
    priority_queue <int,vector<int>,comp> q,temp;
    for(int a=0;a<10;a++){
        int n=rand()%16;
        key[a]=n;
        q.push(a);
    }
    while(!q.empty()){
        temp=q;
        while(!temp.empty()){
            cout<< temp.top() << "(" << key[temp.top()] << ") ";
            temp.pop();
        }
        cout<<endl<<endl;
        int u,v;
        cin>> u >> v;
        key[u]=v;
    }
    return 0;
}

You never changed q. You made a copy of q in temp but never did anything to q.

The intent and the code are reasonable enough, but the issue is much more fundamental. The problem is that std::priority_queue does not support decrease key operation out-of-the-box.

In order to perform such operations, you would need to manually maintain the list of keys and call std::make_heap , std::push_heap from <algorithm> .

See this for a more detailed answer: https://stackoverflow.com/a/9210662/1045285

As a side note, consider instead including:

#include <priority_queue>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM