std::swap

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

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

출처: cppreference

본문

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

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

template< class Key, class T, class Compare, class Alloc >
void swap( std::map<Key, T, Compare, Alloc>& lhs,
           std::map<Key, T, Compare, 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 <map>

int main()
{
    std::map<int, char> alice{{1, 'a'}, {2, 'b'}, {3, 'c'}};
    std::map<int, char> bob{{7, 'Z'}, {8, 'Y'}, {9, 'X'}, {10, 'W'}};

    auto print = [](const std::pair<int, char>& n)
    {
        std::cout << ' ' << n.first << ':' << n.second;
    };

    // swap 전 상태 출력
    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);

    // swap 후 상태 출력
    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:a 2:b 3:c
Bobby: 7:Z 8:Y 9:X 10:W
-- SWAP
Alice: 7:Z 8:Y 9:X 10:W
Bobby: 1:a 2:b 3:c

map의 swap은 내부 트리 노드만 맞바꾸므로 상수 시간에 수행돼요. C++17부터 noexcept가 지정되고, C++20부터 constexpr이에요.

더 알아보기 (Learn more)

cppreference