名稱空間
變體
操作

std::swap(std::queue)

來自 cppreference.com
< cpp‎ | 容器‎ | queue
定義於標頭檔案 <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::swap 演算法以用於 std::queue。交換 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);
 
    // Print state before swap
    print("Alice:", alice);
    print("Bobby:", bob);
 
    std::cout << "-- SWAP\n";
    std::swap(alice, bob);
 
    // Print state after 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)
交換內容
(public member function) [edit]