[英]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. 在下面给出的代码中,我试图将priority_queue中的某些值保持相应的键值排序,这些键值存储在“键”向量中。 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.
在这里,当我将key [8]更改为10时,值8会正确更改其在队列中的位置。 But when I changed the key[2] to -1, it changed it's position in the queue, but not correctly.
但是,当我将key [2]更改为-1时,它更改了它在队列中的位置,但没有正确。 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. 您在
temp
制作了q
的副本,但从未对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. 问题在于
std::priority_queue
不支持立即减少键操作。
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>
. 为了执行此类操作,您需要手动维护键列表,并从
<algorithm>
调用std::make_heap
, std::push_heap
。
See this for a more detailed answer: https://stackoverflow.com/a/9210662/1045285 请参阅此以获得更详细的答案: https : //stackoverflow.com/a/9210662/1045285
As a side note, consider instead including: 作为旁注,请考虑包括以下内容:
#include <priority_queue>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.