pair_swap2
pair_swap2 (std::pair 전용 std::swap 오버로드)
이 페이지는 std::pair 객체의 내용을 교환하는 std::swap 함수 템플릿 오버로드에 대해 설명해요. 이 오버로드는 x.swap(y)와 동일하게 동작하며, C++11부터 사용할 수 있어요. C++20부터는 constexpr로, C++23부터는 const pair에도 사용할 수 있어요.
출처: cppreference
본문
<utility> 헤더에 정의되어 있어요.
| 함수 시그니처 | 오버로드 | 버전 |
|---|---|---|
template < class T1 , class T2 > void swap ( std :: pair < T1 , T2 >& x , std :: pair < T1 , T2 >& y ) noexcept ( /* see below */ ); |
(1) | (since C++11) (until C++20) |
template < class T1 , class T2 > constexpr void swap ( std :: pair < T1 , T2 >& x , std :: pair < T1 , T2 >& y ) noexcept ( /* see below */ ); |
(since C++20) | |
template < class T1 , class T2 > constexpr void swap ( const std :: pair < T1 , T2 >& x , const std :: pair < T1 , T2 >& y ) noexcept ( /* see below */ ); |
(2) | (since C++23) |
x와 y의 내용을 교환해요. x.swap(y)와 동일해요.
오버로드 해석 조건
-
이 오버로드는
std::is_swappable_v<first_type> && std::is_swappable_v<second_type>이true일 때만 오버로드 해석에 참여해요. (since C++17) -
이 오버로드는
std::is_swappable_v<const first_type> && std::is_swappable_v<const second_type>이true일 때만 오버로드 해석에 참여해요. (since C++17)
매개변수
| x, y | - | 내용을 교환할 pair들 |
|---|
예외
noexcept ( noexcept ( x . swap ( y )))
예제
#include <iostream>
#include <utility>
int main()
{
auto p1 = std::make_pair(10, 3.14);
auto p2 = std::pair(12, 1.23); // CTAD, since C++17
auto print_p1_p2 = [&](auto msg) {
std::cout << msg
<< "p1 = {" << std::get<0>(p1)
<< ", " << std::get<1>(p1) << "}, "
<< "p2 = {" << std::get<0>(p2)
<< ", " << std::get<1>(p2) << "}\n";
};
print_p1_p2("Before p1.swap(p2): ");
p1.swap(p2);
print_p1_p2("After p1.swap(p2): ");
std::swap(p1, p2);
print_p1_p2("After swap(p1, p2): ");
}
출력:
Before p1.swap(p2): p1 = {10, 3.14}, p2 = {12, 1.23}
After p1.swap(p2): p1 = {12, 1.23}, p2 = {10, 3.14}
After swap(p1, p2): p1 = {10, 3.14}, p2 = {12, 1.23}
같이 보기
swap |
두 객체의 값을 교환해요 (함수 템플릿) [edit] |
|---|---|
std::swap (std::tuple) (C++11) |
std::swap 알고리즘을 특수화해요 (함수 템플릿) [edit] |