In this C++ tutorial, we will learn how to swap elements between two tuples using swap() function, with example programs.

Swap Elements between two Tuples in C

swap() function swaps the elements between the given two tuples in C++.

Syntax

The syntax of swap() function to swap tuples t1 and t2 is

swap(t1, t2)

Examples

1 Swap contents between two tuples

In the following program, we initialised two tuples: fruit1 and fruit2. We swap the contents of these two tuples using swap() function.

C++ Program

#include <iostream>
#include<tuple>
using namespace std;

int main() {
    tuple<int, string, bool> fruit1(3, "apple", true);
    tuple<int, string, bool> fruit2(7, "banana", false);

    swap(fruit1, fruit2);
    
    cout << "fruit1 : "
        << get<0>(fruit1) << " "
        << get<1>(fruit1) << " "
        << get<2>(fruit1) << " "
        << endl;
    
    cout << "fruit2 : "
        << get<0>(fruit2) << " "
        << get<1>(fruit2) << " "
        << get<2>(fruit2) << " "
        << endl;
}

Output

fruit1 : 7 banana 0 
fruit2 : 3 apple 1 
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to swap elements of two tuples using swap() function, with the help of an example.