C++ priority_queue::swap() 函数



C++ 的std::priority_queue::swap()函数用于高效地交换优先队列,确保交换内容而不改变内容。它保持每个队列中元素的优先级顺序。

swap() 函数可以以两种方式调用:作为成员函数或作为非成员函数。当用作成员函数时,swap() 的时间复杂度为常数,即 O(1),否则当用作非成员函数时为线性,即 O(n)。您可以找到下面两种方法的语法。

语法

以下是 std::priority_queue::swap() 函数的语法。

void swap (priority_queue& x) noexcept;
or
void swap (queue<T,Container,Compare>& q1,queue <T,Container,Compare>& q2) noexcept;

参数

  • x − 表示另一个相同类型的优先队列对象。
  • q1 − 表示第一个 priority_queue 对象。
  • q2 − 表示第二个 priority_queue 对象。

返回值

此函数不返回任何值。

示例

让我们来看下面的例子,我们将交换两个优先队列。

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a, b;
    a.push(1);
    a.push(2);
    b.push(11);
    b.push(22);
    a.swap(b);
    std::cout << "After swapping:";
    std::cout << "\nPriority_queue1: ";
    while (!a.empty()) {
        std::cout << a.top() << " ";
        a.pop();
    }
    std::cout << "\nPriority_queue2: ";
    while (!b.empty()) {
        std::cout << b.top() << " ";
        b.pop();
    }
    return 0;
}

输出

以上代码的输出如下:

After swapping:
Priority_queue1: 22 11 
Priority_queue2: 2 1 

示例

考虑以下示例,我们将交换一个非空队列和一个空队列,并观察输出。

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a, b;
    a.push(1);
    a.push(2);
    a.swap(b);
    std::cout << "After swapping:\n";
    std::cout << "Priority_queue1 is empty";
    std::cout << "\nPriority_queue2: ";
    while (!b.empty()) {
        std::cout << b.top() << " ";
        b.pop();
    }
    return 0;
}

输出

以上代码的输出如下:

After swapping:
Priority_queue1 is empty
Priority_queue2: 2 1 

示例

在下面的示例中,我们将使用带有移动语义的 swap() 函数来交换包含字符串的优先队列。

#include <iostream>
#include <queue>
#include <utility>
int main()
{
    std::priority_queue<std::string> a, b;
    a.push("Hi");
    a.push("Hello");
    b.push("Namaste");
    b.push("Vanakam");
    std::swap(a, b);
    std::cout << "\n\nAfter swapping:\n";
    std::cout << "Priority_queue1: ";
    while (!a.empty()) {
        std::cout << a.top() << " ";
        a.pop();
    }
    std::cout << "\nPriority_queue2: ";
    while (!b.empty()) {
        std::cout << b.top() << " ";
        b.pop();
    }
    return 0;
}

输出

如果我们运行上面的代码,它将生成以下输出:

After swapping:
Priority_queue1: Vanakam Namaste 
Priority_queue2: Hi Hello 
priority_queue.htm
广告
© . All rights reserved.