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;
}
Aucun commentaire:
Enregistrer un commentaire