C++ Tuple::tuple_cat() Function



The C++ std::tuple::tuple_cat() function is used to concatenate the multiple tuples into a single tuple. It accepts any number of tuples as arguments and returns a new tuple containing all the elements from the input tuple. This function enables the composition of the tuples, helping in the operations like merging or appending tuples.

Syntax

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

tuple_cat (Tuples&&... tpls);

Parameters

  • tpls − It separates list of tuple objects. These may be of different types.

Return Value

This function returns a tuple object of the appropriate type to hold args.

Example

In the following example, we are going to combine two tuples of different types.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, double> x(1, 0.04);
    std::tuple<char> y('A');
    auto a = std::tuple_cat(x, y);
    std::cout << std::get<0>(a) << "," << std::get<1>(a)<< "," << std::get<2>(a) <<std::endl;
    return 0;
}

Output

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

1,0.04,A

Example

Consider the another scenario, where we are going to combine the multiple tuples into single tuple.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<double> x(0.01);
    std::tuple<std::string> y("Welcome");
    std::tuple<bool, int> z(false, 1);
    auto a = std::tuple_cat(x, y, z);
    std::cout << std::get<0>(a) << ", " << std::get<1>(a) << ", "
              << std::get<2>(a) << ", " << std::get<3>(a) <<std::endl;
    return 0;
}

Output

Output of the above code is as follows −

0.01, Welcome, 0, 1

Example

Let's look at the following example, where we are trying to combine the empty tuple and observing the output.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<> x;
    std::tuple<> y;
    auto a = std::tuple_cat(x, y);
    std::cout << "Size of the combined tuple: " << std::tuple_size<decltype(a)>::value << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Size of the combined tuple: 0

Example

Following is the example, where we are goign to use the make_tuple() function along with the tuple_cat() function.

#include <iostream>
#include <tuple>
int main()
{
    auto x = std::make_tuple(1, 0.01);
    auto y = std::make_tuple("TutorialsPoint", 'R');
    auto a = std::tuple_cat(x, y);
    std::cout << std::get<0>(a) << ", " << std::get<1>(a) << ", "
              << std::get<2>(a) << ", " << std::get<3>(a) << std::endl;
    return 0;
}

Output

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

1, 0.01, TutorialsPoint, R
Advertisements