Tuples are a type of data structure used to store ordered values. They contain a fixed number of immutable elements.
make_tuple()
is used to assign values in the tuple. The values should be plugged in the same order as the order of data types during the initialization of the tuple.
get()
is used to access the elements stored in the tuple. It takes the element’s index and tuple name as arguments to display the element. It is also used to modify the tuple’s elements.
The code below illustrates how these functions can be used to store, access, and modify the values in a tuple:
#include <iostream>using namespace std;#include <tuple>#include <string>int main() {//Initializing tupletuple <int,string,int> T;/*Plugging in values. Note they are in the same orderas T is initialized.*/T = make_tuple(20,"Hello",30);//printing the values in the tuplecout << "The initial tuple is:\n";cout << "( "<< get<0>(T) << ", " << get<1>(T)<< ", " << get<2>(T)<< " )" << "\n";//modifying the values in the tupleget<0>(T) = 100;get<1>(T) = "Programming is fun";cout<<"The modified tuple is:\n";cout<< "( " << get<0>(T) << ", " << get<1>(T) << ", " <<get<2>(T) << " )";return 0;}
tuple_size()
is used to calculate the number of elements in the tuple.
The following code explains how tuple_size()
works:
#include <iostream>#include <tuple>#include <string>using namespace std;int main() {tuple <int,double,string,string> T;T = make_tuple(40,10.50,"My name","is __");cout<< "Size of the tuple is: " << tuple_size<decltype(T)>::value << "\n";return 0;}
swap()
is used to exchange tuple elements with another tuple of the same type (containing objects of the same types in the same order).
The following code explains how swap()
works:
#include <iostream>#include <tuple>using namespace std;int main (){tuple<int,char> T;tuple<int,char> Y;T = make_tuple(10,'x');Y = make_tuple(20,'y');cout << "Initially, T contains: ( " << get<0>(T) << ", "<<get<1>(T) << " )\n";T.swap(Y);cout << "After swapping, T contains: ( " << get<0>(T) << ", "<<get<1>(T) << " )\n";return 0;}
tuple_cat()
is used to concatenate two tuples and return the resulting tuple.
The following code illustrates how tuple_cat()
is used:
#include <iostream>#include <tuple>using namespace std;int main() {tuple<int,char> T;tuple<int,char> Y;T = make_tuple(10,'x');Y = make_tuple(20,'y');auto concatenated = tuple_cat(T,Y);cout << "The concatenated tuple is: ( " << get<0>(concatenated) << ", "<<get<1>(concatenated) << ", " << get<2>(concatenated) << ", " <<get<3>(concatenated) << " )\n";return 0;}
Tuple | List |
---|---|
Tuples are immutable. | Lists are mutable. |
Tuples can contain different data types. | Lists consist of a singular data type. |
Free Resources