c – 如何告诉std :: priority_queue刷新它的顺序?
作者:互联网
我有一个指向结构城市指针的优先级队列.我修改优先级队列外的这些指针指向的对象,并希望告诉优先级队列根据新值“重新排序”自己.
我该怎么办?
例:
#include <iostream>
#include <queue>
using namespace std;
struct city {
int data;
city *previous;
};
struct Compare {
bool operator() ( city *lhs, city *rhs )
{
return ( ( lhs -> data ) >= ( rhs -> data ) );
}
};
typedef priority_queue< city *, vector< city * >, Compare > pqueue;
int main()
{
pqueue cities;
city *city1 = new city;
city1 -> data = 5;
city1 -> previous = NULL;
cities.push( city1 );
city *city2 = new city;
city2 -> data = 3;
city2 -> previous = NULL;
cities.push( city2 );
city1 -> data = 2;
// Now how do I tell my priority_queue to reorder itself so that city1 is at the top now?
cout << ( cities.top() -> data ) << "\n";
// 3 is printed :(
return 0;
}
解决方法:
这有点hackish,但没有任何违法行为,它完成了工作.
std::make_heap(const_cast<city**>(&cities.top()),
const_cast<city**>(&cities.top()) + cities.size(),
Compare());
更新:
如果出现以下情况,请勿使用此黑客
>底层容器不是矢量.
> Compare仿函数的行为会导致外部副本的顺序与priority_queue中存储的Compare副本不同.
>您不完全了解这些警告的含义.
您始终可以编写自己的容器适配器来包装堆算法. priority_queue只是make / push / pop_heap的一个简单包装器.
标签:c,stl,priority-queue 来源: https://codeday.me/bug/20190930/1837025.html