std::swap

std::swap (std::forward_list 특수화)

std::swap 알고리즘을 std::forward_list에 대해 특수화한 함수예요. 두 리스트의 내용물을 서로 바꿔요. 내부적으로 lhs.swap(rhs)를 호출해요.

출처: cppreference

본문

<forward_list> 헤더에 정의돼 있고, std::forward_listswap 오버로드예요.

template< class T, class Alloc >
void swap( std::forward_list<T, Alloc>& lhs,
           std::forward_list<T, Alloc>& rhs );        // (until C++17)

template< class T, class Alloc >
void swap( std::forward_list<T, Alloc>& lhs,
           std::forward_list<T, Alloc>& rhs )
               noexcept(/* see below */);              // (since C++17)

lhsrhs의 내용물을 서로 바꿔요. 내부적으로 lhs.swap(rhs)를 호출해요.

  • 매개변수 lhs, rhs: 내용물을 바꿀 컨테이너들.
  • 복잡도: 상수 시간.
  • 예외 지정: noexcept(noexcept(lhs.swap(rhs))) (C++17부터).

예제를 보면 swap 전후를 확인할 수 있어요.

#include <algorithm>
#include <iostream>
#include <forward_list>

int main()
{
    std::forward_list<int> alice{1, 2, 3};
    std::forward_list<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

forward_list의 swap은 연결 구조만 맞바꾸므로 상수 시간에 수행돼요. C++17부터 noexcept가 지정되고 상수 시간 swap을 보장해요.

더 알아보기 (Learn more)

cppreference