C++ priority_queue::push() 函式



C++ 的std::priority_queue::push()函式用於根據指定的比較器將元素插入優先佇列。呼叫此函式時,它會根據元素的優先順序(由比較函式確定)將提供的元素新增到佇列中。新元素將放置在一個位置,該位置保持佇列的順序,確保最高優先順序的元素位於最前面。

語法

以下是std::priority_queue::push()函式的語法。

void push (const value_type& val);
or
void push (value_type&& val);

引數

  • val − 表示要分配給新插入元素的值。

返回值

此函式不返回任何值。

示例

讓我們來看下面的例子,我們將演示push()函式的使用。

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> x;
    x.push(1);
    x.push(22);
    x.push(333);
    while (!x.empty()) {
        std::cout << x.top() << " ";
        x.pop();
    }
    return 0;
}

輸出

以下是上述程式碼的輸出:

333 22 1 

示例

考慮以下示例,我們將使用帶有對的push()函式並檢索輸出。

#include <iostream>
#include <queue>
#include <vector>
int main()
{
    std::priority_queue<std::pair<int, std::string>> a;
    a.push(std::make_pair(1, "Namaste"));
    a.push(std::make_pair(2, "Hello"));
    a.push(std::make_pair(3, "Hi"));
    while (!a.empty()) {
        std::cout << a.top().second << " ";
        a.pop();
    }
    return 0;
}

輸出

上述程式碼的輸出如下:

Hi Hello Namaste

示例

在下面的示例中,我們將使用帶有自定義類的優先佇列。

#include <iostream>
#include <queue>
#include <vector>
struct x {
    int priority;
    std::string description;
    bool operator<(const x& other) const
    {
        return priority < other.priority;
    }
};
int main()
{
    std::priority_queue<x> a;
    a.push(x{3, "TutorialsPoint"});
    a.push(x{2, "Tutorix"});
    a.push(x{1, "TP"});
    std::cout << " " << a.top().description << std::endl;
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

TutorialsPoint
priority_queue.htm
廣告