How to use the make_tuple() function in C++
The make_tuple() function is available in the <tuple> header file in C++. This function is used to assign a
Let’s understand with the help of an example.
Example
To create a tuple that contains an integer, float, and character value, we need to execute the code snippet below:
tuple <int,float,char> ex;
ex = make_tuple(1,4.6,'d');
The result is that the data gets stored in the tuple according to the data types inside the tuple.
To create a dynamically typed tuple, the syntax is as shown below:
auto tup = make_tuple(1, 'a');
The statement above will create a tuple
Parameters
There can be none or any number of parameters of the data types as specified when declaring the tuple in the function.
Return value
The function returns a tuple object of the appropriate data type of the arguments.
Code
Let’s have a look at the code.
#include<iostream>#include<tuple>using namespace std;int main(){tuple <int, float, char> tup;tup = make_tuple(2,4.6, 'd');cout << "The values of tuple are : ";cout << get<0>(tup) << ", " << get<1>(tup) << ", " << get<2>(tup) << endl;auto x = make_tuple(1, 'd');cout << "The values of dynamic tuple are : " << get<0>(x) << ", " << get<1>(x);return 0;}
Explanation
-
In lines 1 and 2, we import the required header files.
-
In line 4, we make a
main()function. -
In line 6, we declare a tuple with
int,float, andchardata type parameters, in order. -
In line 8, we use the
make_tuple()function to assign the values of the same data type as the parameters of the tuple. -
In line 10, we display a message about the result of the elements of the tuple.
-
In line 11, we use the
get()method to access the values of the elements of the tuple and display them. -
In line 12, we create a
tuple.dynamic no need to specify the data type and size of the tuple beforehand -
In line 13, we print the data present in our dynamically created tuple.
So, this is the way to use the make_tuple() function to assign values to elements of a tuple.