Tuple in C++ | Programming in C++:
Tuples are objects that pack elements of -heterogeneous types together in a single object. The object of Tuple can be returned from a function too. So, it helps to return multiple values from a function. Eventually, it helps us to avoid creating unnecessary structs.
std::tuple Objtuple { 22, 19.28, “text” };
The below example explains the following points:
1. Retrieve Elements from a std::tuple.
2. Getting Out Of Range value from the tuple.
3. Wrong typecast in case of getting value from the tuple.
4. Value from a tuple by dynamic index.
std::tuple RetunTuple()
{
// Creating a tuple of int, double and string.
std::tuple objtuple(7, 9.8, “text”);
// Returning tuple object.
return objtuple;
}
int main()
{
//1. Get tuple object from a function.
std::tuple objTuple= RetunTuple();
//2. Get values from tuple.
// First int value from tuple.
int iVal = std::get < 0 > (objTuple);
// Second double value from tuple.
double dVal = std::get < 1 > (objTuple);
// Third string value from tuple.
std::string strVal = std::get < 2 > (objTuple);
// 3. Index 4 cause compiler error- Invalid Index.
//int iVal2 = std::get(objTuple); // Compile error
//4. Wrong cast will force compile time error.
//std::string strVal2 = std::get(objTuple); // Compile error
int x = 1;
//5. Integer x should be constant.
//double dVal2 = std::get(objTuple); //Compiler Error
const int i = 1;
// Get second double value from tuple.
double dVal3 = std::get < i > (objTuple);
return 0;
}
tuple continuation: Use of make_tuple in C++.
External links for reference:
Cppreference Link for Tuple: https://en.cppreference.com/w/cpp/utility/tuple
Wiki Reference for Tuple : https://en.wikipedia.org/wiki/C%2B%2B11#Tuple_types