Namespaces
Variants

std::priority_queue<T,Container,Compare>:: swap

From cppreference.net

void swap ( priority_queue & other ) noexcept ( /* see below */ ) ;
(C++11 起)
Exchanges the contents of the container adaptor with those of other . Effectively calls
using std::swap;
swap(c, other.c);
swap(comp, other.comp);

目录

参数

其他 - 用于交换内容的容器适配器

返回值

(无)

异常

noexcept 规范:
noexcept ( noexcept ( swap ( c, other. c ) ) && noexcept ( swap ( comp, other. comp ) ) )

在上述表达式中,标识符 swap 的查找方式与 C++17 特性 std::is_nothrow_swappable 使用的方式相同。

(C++11 起)
(C++17 前)
noexcept 规范:
noexcept ( std:: is_nothrow_swappable_v < Container > &&
std:: is_nothrow_swappable_v < Compare > )
(C++17 起)

复杂度

与底层容器相同(通常为常量)。

注释

某些实现(例如 libc++)在 C++11 之前的模式中提供了 swap 成员函数作为扩展功能。

示例

#include <iostream>
#include <concepts>
#include <functional>
#include <queue>
#include <string>
#include <string_view>
#include <vector>
template<typename Adaptor>
requires (std::ranges::input_range<typename Adaptor::container_type>)
void print(std::string_view name, const Adaptor& adaptor)
{
    struct Printer : Adaptor // 用于访问受保护的 Adaptor::Container c;
    {
        void print(std::string_view name) const
        {
            std::cout << name << " [" << std::size(this->c) << "]: ";
            for (auto const& elem : this->c)
                std::cout << elem << ' ';
            std::cout << '\n';
        }
    };
    static_cast<Printer const&>(adaptor).print(name);
}
int main()
{
    std::vector<std::string> v1{"1","2","3","4"},
                             v2{"Ɐ","B","Ɔ","D","Ǝ"};
    std::priority_queue s1(std::less<>(), std::move(v1));
    std::priority_queue s2(std::less<>(), std::move(v2));
    print("s1", s1);
    print("s2", s2);
    s1.swap(s2);
    print("s1", s1);
    print("s2", s2);
}

输出:

s1 [4]: 4 3 2 1
s2 [5]: Ǝ D Ɔ B Ɐ
s1 [5]: Ǝ D Ɔ B Ɐ
s2 [4]: 4 3 2 1

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 2456 C++11 noexcept 规范格式错误 已修复可用

另请参阅

特化 std::swap 算法
(函数模板)