C++ Tuple::get() Function



The C++ std::tuple::get() function allows you to access the elements stored in the tuple by index. It takes the tuple and an index as an arguments and returns the value at that index. The index must be known at compile time and must be within the range of tuples. For instance, std::get<0>(mytuple) retrieves the first element.

When we try to access the index that is of out of range will lead to a run time error.

Syntax

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

typename tuple_element< I, tuple<Types...> >::type& get(tuple<Types...>& tpl) noexcept;

Parameters

  • I − It indicates the position of element.
  • Types − It indicates the type of element.
  • tpl − It indicates the tuple object with more than I elements.

Return Value

This funcion returns a reference to the Ith element of tuple tpl.

Example

Let's look at the following example, where we are goign to access the first element of the tuple.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, float, std::string> x(1, 0.04, "Welcome");
    int firstElement = std::get<0>(x);
    std::cout << " " << firstElement << std::endl;
    return 0;
}

Output

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

1

Example

Consider the another scenario, where we are going to access the third element of the tuple.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, float, std::string> x(10, 3.14, "TutorialsPoint");
    std::string thirdElement = std::get<2>(x);
    std::cout << " " << thirdElement << std::endl;
    return 0;
}

Output

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

TutorialsPoint

Example

In the following example, we are going to use the std::tie to extract multiple elements from a tuple.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, float, std::string> x(1, 0.04, "TP");
    int first;
    float second;
    std::tie(first, second, std::ignore) = x;
    std::cout << "1st Element: " << first << ", 2nd Element: " << second << std::endl;
    return 0;
}

Output

Following is the output of the above code −

1st Element: 1, 2nd Element: 0.04

Example

Following is the example, where we are going to use the get() function and modifying the tuple.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, std::string, double> x(1, "TP", 0.02);
    std::get<1>(x) = "TutorialsPoint";
    std::cout << "After Modification: " << std::get<0>(x) << ", " << std::get<1>(x) << ", " << std::get<2>(x) << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

After Modification: 1, TutorialsPoint, 0.02
Advertisements