2014-11-02 157 views
6

我想實現一個A *算法,我需要一個優先級隊列,但std::priority_queue不適合我,因爲我需要找到一個元素(一個Node對象)是否在priority_queue中,以訪問其數據並在必要時進行修改。C++優先級隊列查找和修改對象

我能以某種方式使用std::priority_queue嗎?

我會很感激代碼的建議,因爲我沒有太多的經驗std::priority_queue

+1

你不能使用front()並遍歷它嗎? – 2501 2014-11-02 14:41:51

+0

boost :: bimap呢? – 2014-11-02 15:24:09

+1

請注意,標準庫容器通常會在效率低下時避免提供操作。在通常的優先級隊列實現(使用堆)中,搜索和成員資格測試具有O(N)複雜性,這可能是爲什麼此操作不是內置的。這可能會或可能不會成爲您的應用程序的問題。只要注意你需要多久才需要測試會員資格。 – 2014-11-02 15:43:30

回答

1

「,但在STL :: priority_queue不適合我,因爲我需要找到一個元素(節點對象)是否在priority_queue與否,訪問其數據,如果對其進行修改必要。」

可以很好的任何一種類的設置適當的Compare類參數做到這一點。

std::priority_queue<T>要求底層Container符合SequenceContainer的概念。

template< 
    class T, 
    class Container = std::vector<T>, 
    class Compare = std::less<typename Container::value_type> 
> class priority_queue; 

可以採取std::priority_queue<T>::front()參考的地址,並通過隊列迭代,找某些情況下。


如果你真的需要有對象的唯一存在的情況下,應另外一些優先級算法來管理,也可能是存儲智能指針是一個好主意(如std::shared_ptr<T>),而不是值或原始指針。課程當然需要適當調整。


struct CompareNodes { 
    bool operator 
     (const std::shared_ptr<Node>& lhs 
     , const std::shared_ptr<Node>& rhs 
     ) { 
     // Provide some operation to compare lhs < rhs (less) results in true 
     // This function is meant to determine the actual priority of your Node 
     // instances, when referenced in the priority_queue<> in question. 
    } 
}; 

std::priority_queue 
    < std::shared_ptr<Node> 
    , std::vector<std::shared_ptr<Node>> 
    , CompareNodes 
    > myQueue; 

「即可訪問其數據,並在必要時對其進行修改。」

使用優先級隊列std::shared_ptr如上述樣品中,也可以從連放了你需要找到實例在隊列中,並同步從原始實例數據修改。

+0

'value_type'應該放在'class Compare = std :: less '中嗎? – mariya 2014-11-02 15:33:55

+1

@ mariya至於我的示例'std :: shared_ptr '。你必須自己實現這個,因爲我試着在我的示例中用'CompareNodes'來演示。 – 2014-11-02 15:39:21