Namespaces
Variants
Views
Actions

std::pair::swap

From cppreference.com
< cpp‎ | utility‎ | pair
void swap(pair& other) noexcept(/* see below */);
(since C++11)

Swaps first with other.first and second with other.second.

This function does not participate in overload resolution unless std::is_swappable_v<first_type> && std::is_swappable_v<second_type> is true.

(since C++17)

Contents

[edit] Parameters

other - pair of values to swap

[edit] Return value

(none)

[edit] Exceptions

noexcept specification:  
noexcept(

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

)

In the expression above, the identifier swap is looked up in the same manner as the one used by the C++17 std::is_nothrow_swappable trait.

(until C++17)
noexcept specification:  
noexcept(

     std::is_nothrow_swappable<first_type>::value) &&
     std::is_nothrow_swappable<second_type>::value)

)
(since C++17)

[edit] Example

#include <iostream>
#include <utility>
#include <string>
int main()
{
    std::pair<int, std::string> p1, p2;
    p1 = std::make_pair(10, "test");
    p2.swap(p1);
    std::cout << "(" << p2.first << ", " << p2.second << ")\n";
}

Output:

(10, test)

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 2456 C++11 the noexcept specification is ill-formed made to work

[edit] See also

swaps the values of two objects
(function template) [edit]