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 ( /* see below */ ) ;
(C++17以降)
(constexpr C++26以降)
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)
内容を交換する
(公開メンバ関数)