Namespaces
Variants

std::pair<T1,T2>::swap

cppreference.net에서 가져옴
 
 
유틸리티 라이브러리
일반 유틸리티
관계 연산자 (C++20에서 폐지됨)
정수 비교 함수
(C++20)(C++20)(C++20)    
(C++20)
Swap 및 타입 연산
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
공통 어휘 타입
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
void swap( pair& other ) noexcept(/* see below */);
(1) (C++11부터)
(C++20부터 constexpr)
constexpr void swap( const pair& other ) const noexcept(/* see below */);
(2) (C++23부터)

first과 other.first를, 그리고 second과 other.second를 마치 using std::swap; swap(first, other.first); swap(second, other.second);인 것처럼 바꿉니다.

선택된 swap 함수 호출이 제대로 된 형식이 아니거나 멤버의 값을 바꾸지 않는 경우, 동작은 정의되지 않습니다.

(C++23까지)
1) std::is_swappable_v<T1> 또는 std::is_swappable_v<T2>가 true가 아니라면 프로그램의 형식이 잘못되었습니다.
2) std::is_swappable_v<const T1> 또는 std::is_swappable_v<const T2>가 true가 아니라면 프로그램의 형식이 잘못되었습니다.

선택된 swap 함수 호출이 멤버의 값을 바꾸지 않는 경우, 동작은 정의되지 않습니다.

(C++23부터)

매개변수

other - 교환할 값의 쌍

예외

noexcept 명세:
noexcept (

noexcept ( swap ( first, other. first ) ) &&
noexcept ( swap ( second, other. second ) )

)

위 표현식에서 식별자 swap 은 C++17 std::is_nothrow_swappable 특성이 사용하는 방식과 동일한 방식으로 조회됩니다.

(C++17 이전)
1)
noexcept 명세:
noexcept (

std:: is_nothrow_swappable_v < first_type > &&
std:: is_nothrow_swappable_v < second_type >

)
2)
noexcept 명세:
noexcept (

std:: is_nothrow_swappable_v < const first_type > &&
std:: is_nothrow_swappable_v < const second_type >

)
(C++17 이후)

예제

#include <iostream>
#include <utility>
#include <string>
int main()
{
    std::pair<int, std::string> p1(10, "test"), p2;
    p2.swap(p1);
    std::cout << "(" << p2.first << ", " << p2.second << ")\n";
#if __cpp_lib_ranges_zip >= 202110L
    // C++23 const 한정 swap 오버로드 사용
    // (swap은 더 이상 pair의 constness를 전파하지 않음)
    int i1 = 10, i2{};
    std::string s1("test"), s2;
    const std::pair<int&, std::string&> r1(i1, s1), r2(i2, s2);
    r2.swap(r1);
    std::cout << "(" << i2 << ", " << s2 << ")\n";
#endif
}

가능한 출력:

(10, test)
(10, test)

결함 보고서

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 발표된 동작 올바른 동작
LWG 2456 C++11 noexcept 명세가 잘못 구성됨 작동하도록 수정됨

참고 항목

두 객체의 값을 교환
(함수 템플릿)
두 tuple 의 내용을 교환
( std::tuple<Types...> 의 public 멤버 함수)