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.
SyntaxWhen we try to access the index that is of out of range will lead to a run time error.
Following is the syntax for std::tuple::get() function.
typename tuple_element< I, tuple<Types...> >::type& get(tuple<Types...>& tpl) noexcept;Parameters
This funcion returns a reference to the Ith element of tuple tpl.
ExampleLet'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 −
1Example
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 −
TutorialsPointExample
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.04Example
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4