C++ Tuple::tie() Function



The C++ std::tuple::tie() function is used to help the binding of multiple variables to the elements of a tuple. Essentially, it allows for the unpacking of a tuple values directly into specified variables. It is mainly useful in the scenarios where you want to decompose the elements of the tuple into separate variables for further manipulation.

The tie() function can be employed in conjunction with other operations likes comparison and sorting.

Syntax

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

tie( Types&... args ) noexcept;

Parameters

  • args − It contains a list of elements that the constructed tuple shall contain.

Example

Let's look at the following example, where we are going to swap the values of two variables using tie() with make_tuple().

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    int x = 11, y = 111;
    tie(x, y) = make_tuple(y, x);
    cout << "x: " << x << ", y: " << y << endl;
    return 0;
}

Output

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

x: 111, y: 11

Example

Consider the another scenario, where we are going to unpack the tuple data into separate variables using tie() function.

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    tuple<float, string> data = make_tuple(0.01, "Welcome");
    float x;
    string y;
    tie(x,y) = data;
    cout << "x: " << x << ", y: " << y <<endl;
    return 0;
}

Output

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

x: 0.01, y: Welcome

Example

In the following example, only the second element of the tuple data is unpacked into variable, while other elements are ignored.

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    tuple<int, string> data = make_tuple(42, "TutorialsPoint");
    string x;
    tie(ignore, x) = data;
    cout << "x: " << x << endl;
    return 0;
}

Output

Following is the output of the above code −

x: TutorialsPoint
Advertisements