簡體   English   中英

如何使用priority_queue的push()?

[英]How to use the push() of priority_queue?

這就是我所擁有的

priority_queue<int, vector<string>, std::greater<int>> Jobs1;

我該怎么做push()?

vector<string> temp;
// Jobs1.push(what goes in here?) <---- I want to push temp in this min heap, and let's say my compare value is 3

謝謝!

正如其他答案所言,priority_queue與其他容器類型一樣,保存特定類型的單個項目。

您的問題和其他注釋建議您要存儲一堆字符串,並按任意優先級數字排序。 為此,您需要創建自己的類型,其中包括字符串及其優先級。 如果提供自己的operator<operator>重載,則標准比較功能也將起作用。

這是實現此類的一種方法的簡單示例,以及如何使用它。 它使用C ++ 11功能,例如擴展的初始化程序列表和auto。

#include <iostream>
#include <queue>
#include <string>

class PriorityString
{
public:
        int priority;
        std::string value;

        PriorityString(int _priority, std::string const stringvalue)
        : priority    (_priority)
        , value       (stringvalue)
        {
        }

        bool operator< (PriorityString const& other) const
        {
                return priority < other.priority;
        }

        bool operator> (PriorityString const& other) const
        {
                return priority > other.priority;
        }
};

int
main()
{
        std::priority_queue< PriorityString, std::vector<PriorityString>, std::less<PriorityString> > strings;

        strings.push( {1, "Alice"} );
        strings.push( {2, "Bob"} );
        strings.push( {4, "Charlie"} );
        strings.push( {3, "Dianne"} );

        while (! strings.empty() )
        {
                auto const& ps = strings.top();
                std::cout << "Priority: " << ps.priority << "  V: " << ps.value << std::endl;
                strings.pop();
        }
}

這將輸出:

Priority: 4  V: Charlie
Priority: 3  V: Dianne
Priority: 2  V: Bob
Priority: 1  V: Alice

如果將std::less替換為std::greater則它們將以優先級升序打印(即,較低優先級將排在隊列的最前面)。

如果您無權使用C ++ 11功能,則可以使用顯式構造函數來添加項目:

strings.push( PriorityString(1, "Alice") );

strings.top()的返回類型當然是對PriorityString的常量引用。

根據您要實現的目標,您可能還需要查看STL的mapset類型以及它們的無序變體。 如果您始終希望以固定的順序處理商品,則類似“ PriorityString”的設置很有用,並且在添加新商品以確定它們在訂單中的位置時可以容忍(潛在地)冗長的操作。

基礎容器應存儲int而不是string

vector<string>應該實際上是vector<int>

#include <iostream>
#include <queue> 

using namespace std;

int main()
{    
    priority_queue<int, vector<int>, std::greater<int>> Jobs1;
    Jobs1.push(3);
    Jobs1.push(4);
    Jobs1.push(5);
    //..    
}

push()用於將元素插入優先級隊列。 因此,要將int插入優先級隊列,請使用:

int a = 5;
Jobs1.push(a);

另外,由於優先級隊列用於整數,因此基礎容器應為vector<int>而不是vector<string>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM