C++ Tuple::swap() Function



The C++ std::tuple::swap() function is used to exchange the elements of two tuples of the same type, it swaps the values within the tuples avoiding unnecessary copies. This function is particularly useful for swapping multiple variables simultaneously.

By using the move semantics, swap() function improves it performance by moving elements instead of copying them. It provides a convenient way to exchange values between tuples without explicitly iterating through each element.

Syntax

Following is the syntax for std::tuple::swap() function.

void swap (tuple& tpl) noexcept

Parameters

tpl − It is an another tuple object of the same type.

Return Value

This function does not return anything.

Example

Let's look at the following example, where we are going to swap the two tuples.

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    tuple<int, int> x = make_tuple(11,12);
    tuple<int, int> y = make_tuple(13,14);
    swap(x, y);
    cout << "x after swap: " << get<0>(x) << ", " << get<1>(x) << endl;
    cout << "y after swap: " << get<0>(y) << ", " << get<1>(y) << endl;
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

x after swap: 13, 14
y after swap: 11, 12

Example

Consider the another scenario, where we are going to swap the elements of the tuple.

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    tuple<int, string> x = make_tuple(1, "Vespa");
    tuple<int, string> y = make_tuple(2, "Activa");
    swap(get<1>(x), get<1>(y));
    cout << "x after swap: " << get<0>(x) << ", " << get<1>(x) << endl;
    cout << "y after swap: " << get<0>(y) << ", " << get<1>(y) << endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

x after swap: 1, Activa
y after swap: 2, Vespa

Example

In the followig example, we are going to swap a tuple in a vector.

#include <iostream>
#include <vector>
#include <tuple>
int main()
{
    std::vector<std::tuple<int, int>> x{{1, 2}, {11, 22}};
    std::swap(x[0], x[1]);
    std::cout << "After swapping:\n";
    for (const auto& a : x) {
        std::cout << std::get<0>(a) << " " << std::get<1>(a) << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

After swapping:
11 22
1 2

Example

Let's consider the following example, where we are going to swap the empty tuples.

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    tuple<int, string> x;
    tuple<int, string> y;
    swap(x, y);
    cout << "x after swap: (" << get<0>(x) << ", " << get<1>(x) << ")" << endl;
    cout << "y after swap: (" << get<0>(y) << ", " << get<1>(y) << ")" << endl;
    return 0;
}

Output

Output of the above code is as follows −

x after swap: (0, )
y after swap: (0, )
Advertisements