本文介绍了如何告诉std :: priority_queue刷新它的排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个指向结构的指针的优先级队列,例如。市。我编辑优先级队列之外的指针,并希望根据新的值告诉优先级队列重新排序自己。
I have a priority queue of pointers to a struct, e.g. city. I edit the pointers outside the priority queue, and want to tell the priority queue to "reorder" itself according to the new values.
我该怎么办?
例如
#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; }
b $ b
谢谢。
Thanks.
推荐答案
这是一个有点黑,但没有违法,完成。
This is a bit hackish, but nothing illegal about it, and it gets the job done.
std::make_heap(const_cast<city**>(&cities.top()), const_cast<city**>(&cities.top()) + cities.size(), Compare());
更新:
如果出现以下情况,请勿使用此黑客:
Do not use this hack if:
- 底层容器不是向量。
- 比较函子的行为会导致您的外部副本与比较 > priority_queue 。
- 您不完全明白这些警告的含义。
- The underlying container is not vector.
- The Compare functor has behavior that would cause your external copy to order differently than the copy of Compare stored inside the priority_queue.
- You don't fully understand what these warnings mean.
你总是可以编写自己的包装堆算法的容器适配器。 priority_queue 只是一个简单的包装器 make / push / pop_heap 。
You can always write your own container adaptor which wraps the heap algorithms. priority_queue is nothing but a simple wrapper around make/push/pop_heap.
这篇关于如何告诉std :: priority_queue刷新它的排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!