std::swap(std::queue)

出自cppreference.com
在標頭 <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 起)

std::queue 特化了 std::swap 算法。交換 lhsrhs 的內容。調用 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);

    // 打印 swap 之前的状态
    print("Alice:", alice);
    print("Bobby:", bob);

    std::cout << "-- SWAP\n";
    std::swap(alice, bob);

    // 打印 swap 之后的状态
    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)
交換內容
(公開成員函數) [編輯]