Namespaces
Variants

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

From cppreference.net
Utilities library
(1)
void swap ( pair & other ) noexcept ( /* see below */ ) ;
(C++11부터)
(C++20까지)
constexpr void swap ( pair & other ) noexcept ( /* see below */ ) ;
(C++20부터)
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 멤버 함수)