Namespaces
Variants

std:: swap (std::queue)

From cppreference.net

定义于头文件 <queue>
template < class T, class Container >

void swap ( std:: queue < T, Container > & lhs,

std:: queue < T, Container > & rhs ) ;
(C++11 起)
(C++17 前)
template < class T, class Container >

void swap ( std:: queue < T, Container > & lhs,
std:: queue < T, Container > & rhs )

noexcept ( /* 见下文 */ ) ;
(C++17 起)
(C++26 起为 constexpr)
Specializes the std::swap algorithm for std::queue . Swaps the contents of lhs and rhs . Calls lhs. swap ( rhs ) .

此重载仅当 std:: is_swappable_v < Container > true 时参与重载决议。

(C++17 起)

目录

参数

lhs, rhs - 要交换内容的容器

复杂度

等同于交换底层容器。

异常处理

noexcept 规范:
noexcept ( noexcept ( lhs. swap ( rhs ) ) )
(C++17 起)

注释

尽管容器适配器的 std::swap 重载是在C++11中引入的,但在C++98中容器适配器已经可以通过 std::swap 进行交换。此类对 std::swap 的调用通常具有线性时间复杂度,但也可能提供更优的时间复杂度。

示例

#include <algorithm>
#include <iostream>
#include <queue>
int main()
{
    std::queue<int> alice;
    std::queue<int> bob;
    auto print = [](const auto& title, const auto& cont)
    {
        std::cout << title << " size=" << cont.size();
        std::cout << " front=" << cont.front();
        std::cout << " back=" << cont.back() << '\n';
    };
    for (int i = 1; i < 4; ++i)
        alice.push(i);
    for (int i = 7; i < 11; ++i)
        bob.push(i);
    // 交换前的状态打印
    print("Alice:", alice);
    print("Bobby:", bob);
    std::cout << "-- SWAP\n";
    std::swap(alice, bob);
    // 交换后的状态打印
    print("Alice:", alice);
    print("Bobby:", bob);
}

输出:

Alice: size=3 front=1 back=3
Bobby: size=4 front=7 back=10
-- SWAP
Alice: size=4 front=7 back=10
Bobby: size=3 front=1 back=3

参见

(C++11)
交换内容
(公开成员函数)