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
广告
© . All rights reserved.