名稱空間
變體
操作

std::swap(std::priority_queue)

來自 cppreference.com
定義於標頭檔案 <queue>
template< class T, class Container, class Compare >

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

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

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

               noexcept(/* 見下 */);
(C++17 起)
std::priority_queue 特化 std::swap 演算法。交換 lhsrhs 的內容。呼叫 lhs.swap(rhs)

此過載僅若 std::is_swappable_v<Container>std::is_swappable_v<Compare> 均為 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::priority_queue<int> alice;
    std::priority_queue<int> bob;
 
    auto print = [](const auto& title, const auto& cont)
    {
        std::cout << title << " size=" << cont.size();
        std::cout << " top=" << cont.top() << '\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 top=3
Bobby: size=4 top=10
-- SWAP
Alice: size=4 top=10
Bobby: size=3 top=3

[編輯] 參閱

(C++11)
交換內容
(公開成員函式) [編輯]