std::swap(std::set)

出自cppreference.com
 
 
 
 
在標頭 <set> 定義
template< class Key, class Compare, class Alloc >
void swap( std::set<Key, Compare, Alloc>& lhs,
           std::set<Key, Compare, Alloc>& rhs );
(C++17 前)
template< class Key, class Compare, class Alloc >
void swap( std::set<Key, Compare, Alloc>& lhs,
           std::set<Key, Compare, Alloc>& rhs )
               noexcept(/* 见下文 */);
(C++17 起)

std::set 特化了 std::swap 算法。交換 lhsrhs 的內容。調用 lhs.swap(rhs)


參數

lhs, rhs - 要交換內容的容器

返回值

(無)

複雜度

常數。

異常

noexcept 說明:  
noexcept(noexcept(lhs.swap(rhs)))
(C++17 起)

示例

#include <algorithm>
#include <iostream>
#include <set>

int main()
{
    std::set<int> alice{1, 2, 3};
    std::set<int> bob{7, 8, 9, 10};

    auto print = [](const int& n) { std::cout << ' ' << n; };

    // 打印交换前的状态
    std::cout << "Alice:";
    std::for_each(alice.begin(), alice.end(), print);
    std::cout << "\nBobby:";
    std::for_each(bob.begin(), bob.end(), print);
    std::cout << '\n';

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

    // 打印交换后的状态
    std::cout << "Alice:";
    std::for_each(alice.begin(), alice.end(), print);
    std::cout << "\nBobby:";
    std::for_each(bob.begin(), bob.end(), print);
    std::cout << '\n';
}

輸出:

Alice: 1 2 3
Bobby: 7 8 9 10
-- SWAP
Alice: 7 8 9 10
Bobby: 1 2 3

參閱

交換內容
(公開成員函數) [編輯]