# std::swap(std::tuple)

> C++ Atlas: `cppatlas.com/w/cpp/utility/tuple/swap2` | Source: https://en.cppreference.com/w/cpp/utility/tuple/swap2 | Domain: Utility | Standards: C++11, C++17, C++20, C++23

Swaps the contents of lhs and rhs. Equivalent to lhs.swap(rhs).

## Official Specification Summary (cppreference)

```cpp
// Defined in header <tuple>

template< class... Types >
void swap( std::tuple<Types...>& lhs,
           std::tuple<Types...>& rhs ) noexcept(/* see below */); // (1) (since C++11) (until C++20)

template< class... Types >
constexpr void swap( std::tuple<Types...>& lhs,
                     std::tuple<Types...>& rhs ) noexcept(/* see below */); // (1) (since C++20)

template< class... Types >
constexpr void swap( const std::tuple<Types...>& lhs,
                     const std::tuple<Types...>& rhs ) noexcept(/* see below */); // (2) (since C++23)
```

Swaps the contents of `lhs` and `rhs`. Equivalent to `lhs.swap(rhs)`.

(since C++17):

1) This overload participates in overload resolution only if `std::is_swappable_v<Ti>` is `true` for all i from 0 to `sizeof...(Types)`.

2) This overload participates in overload resolution only if `std::is_swappable_v<const Ti>` is `true` for all i from 0 to `sizeof...(Types)`.

### Parameters

- `lhs, rhs` - tuples whose contents to swap

### Return value

(none)

### Exceptions

`noexcept` specification:

`noexcept(noexcept(lhs.swap(rhs)))`

### Example

```cpp
#include <iostream>
#include <string>
#include <tuple>

int main()
{
    std::tuple<int, std::string, float> p1{42, "ABCD", 2.71}, p2;
    p2 = std::make_tuple(10, "1234", 3.14);

    auto print_p1_p2 = [&](auto rem)
    {
        std::cout << rem
                  << "p1 = {" << std::get<0>(p1)
                  << ", "     << std::get<1>(p1)
                  << ", "     << std::get<2>(p1) << "}, "
                  << "p2 = {" << std::get<0>(p2)
                  << ", "     << std::get<1>(p2)
                  << ", "     << std::get<2>(p2) << "}\n";
    };

    print_p1_p2("Before p1.swap(p2): ");
    p1.swap(p2);
    print_p1_p2("After  p1.swap(p2): ");
    swap(p1, p2);
    print_p1_p2("After swap(p1, p2): ");
}
```

Output:

```text
Before p1.swap(p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14}
After  p1.swap(p2): p1 = {10, 1234, 3.14}, p2 = {42, ABCD, 2.71}
After swap(p1, p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14}
```

### See also

- [`swap`](https://en.cppreference.com/w/cpp/utility/tuple/swap): swaps the contents of two `tuple`s (public member function)
- [`std::swap(std::pair)`](https://en.cppreference.com/w/cpp/utility/pair/swap2) (C++11): specializes the `std::swap` algorithm (function template)

---
Attribution: content from https://en.cppreference.com/w/cpp/utility/tuple/swap2 (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.