tuple and pair are very similar in their structure. Just like in pair we can pair two heterogeneous object, in tuple we can pair three heterogeneous objects. The elements of tuples are initialized as arguments in order in which they will be accessed.
Operations on tuple
- get() :- Used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element.
- make_tuple() :- Used to assign tuple with values. The values passed should be in order with the values declared in tuple.
Commonly used Functions
Similar to pair, tuple template has its own member and non-member functions, few of which are listed below :
- A Constructor to construct a new tuple
- Operator = : to assign value to a tuple
- swap : to swap value of two tuples
- make_tuple() : creates and return a tuple having elements described by the parameter list.
- Operators( == , != , > , < , <= , >= ) : lexicographically compares two pairs.
- Tuple_element : returns the type of tuple element
- Tie : Tie values of a tuple to its references.
Example
#include <iostream> int main () { // Creates tuple of integers tuple<int, int, int> tuple1; // Creates pair of an integer an 2 string tuple<int, string, string> tuple2; // Tuple with four element auto bar = make_tuple ("test", 3.1, 14, 'y'); // Insert tuple1 = make_tuple(1,2,3); tuple2 = make_tuple(1,"SH", "LY"); int id; string first_name, last_name; // Tie id, first_name, last_name to first, second and third element tie(id,first_name,last_name) = tuple2; // Prints 1 SH LY cout << id <<" "<< first_name <<" "<< last_name; // Printing tuple values using get() cout << get<0>(tuple1) << " " << get<1>(tuple1) << " " << get<2>(tuple1) << endl; // Change values of tuple get<0>(tuple1) = 8 get<2>(tuple1) = 9; // Use of size to find tuple_size of tuple cout <<tuple_size<decltype(tuple1)>::value << endl; // Swapping tup1 values with tup2 tuple <int,char,float> tup1(20,'g',17.5); tuple <int,char,float> tup2(10,'f',15.5); tup1.swap(tup2); // Concatenating 2 tuples to return a new tuple auto tup3 = tuple_cat(tup1,tup2); return 0; }