C++ priority_queue::operator=() 函式



C++ 的 std::priority_queue::operator=() 函式用於將一個優先佇列的內容賦值給另一個優先佇列。它確保目標優先佇列成為源優先佇列的精確副本,具有相同的元素和排序。

它處理複製和移動語義,根據源是左值(複製)還是右值(移動)提供高效的操作。您可以在下面找到兩種變體的語法。此函式的時間複雜度為線性,即 O(n)。

語法

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

operator=( const priority_queue<T,Container>& other );
or
operator=( priority_queue<T,Container>&& other );

引數

  • other − 指示另一個相同型別的優先佇列物件。

返回值

此函式返回 this 指標。

示例

在下面的示例中,我們將演示賦值運算子的基本用法。

#include <iostream>
#include <queue>
#include <vector>
int main()
{
    std::priority_queue<int> a;
    a.push(1);
    a.push(2);
    std::priority_queue<int> b;
    b.push(3);
    b.push(4);
    b = a;
    while (!b.empty()) {
        std::cout << b.top() << " ";
        b.pop();
    }
    return 0;
}

輸出

上述程式碼的輸出如下:

2 1

示例

考慮以下示例,我們將優先佇列賦值給自己。

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

輸出

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

3 2 1 

示例

在下面的示例中,我們將使用賦值運算子將初始為空的優先佇列賦值給另一個優先佇列。

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    std::priority_queue<int> b;
    b.push(20);
    b.push(30);
    b = a;
    std::cout << "Size of the queue2 after assigning: " << b.size();
    return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Size of the queue2 after assigning: 0
priority_queue.htm
廣告