How to Use std::get with std::tuple in C++
In C++, you use
std::get to access elements inside a std::tuple by specifying either the element's index or its type. For example, std::get<0>(myTuple) gets the first element, and std::get<Type>(myTuple) gets the element of that type if it is unique.Syntax
The std::get function has two main forms to access tuple elements:
- By index:
std::get<Index>(tuple)whereIndexis a compile-time constant starting from 0. - By type:
std::get<Type>(tuple)whereTypeis the type of the element you want to access. This requires the type to appear exactly once in the tuple.
Both forms return a reference to the element, allowing you to read or modify it.
cpp
std::tuple<int, double, std::string> myTuple(10, 3.14, "hello"); // Access by index int a = std::get<0>(myTuple); // a = 10 // Access by type double b = std::get<double>(myTuple); // b = 3.14
Example
This example shows how to create a tuple, access its elements by index and by type, and modify an element using std::get.
cpp
#include <iostream> #include <tuple> #include <string> int main() { std::tuple<int, double, std::string> myTuple(42, 2.718, "world"); // Access elements by index int i = std::get<0>(myTuple); double d = std::get<1>(myTuple); std::string s = std::get<2>(myTuple); std::cout << "By index: " << i << ", " << d << ", " << s << '\n'; // Access element by type double d2 = std::get<double>(myTuple); std::cout << "By type (double): " << d2 << '\n'; // Modify element std::get<2>(myTuple) = "C++"; std::cout << "Modified string: " << std::get<2>(myTuple) << '\n'; return 0; }
Output
By index: 42, 2.718, world
By type (double): 2.718
Modified string: C++
Common Pitfalls
Common mistakes when using std::get with tuples include:
- Using an index out of range, which causes a compile-time error.
- Using
std::get<Type>when the type appears multiple times in the tuple, which causes ambiguity and a compile-time error. - Trying to use
std::getwithout including the<tuple>header.
Always ensure the index is valid and the type is unique when using type-based access.
cpp
#include <tuple> int main() { std::tuple<int, int> t(1, 2); // Wrong: type int appears twice, this causes error // int x = std::get<int>(t); // ERROR: ambiguous // Correct: use index int x = std::get<0>(t); int y = std::get<1>(t); return 0; }
Quick Reference
Summary tips for using std::get with tuples:
- Use
std::get<index>(tuple)to access elements by position starting at 0. - Use
std::get<Type>(tuple)only if the type is unique in the tuple. - Include
<tuple>header to usestd::tupleandstd::get. - Accessed elements can be modified if the tuple is not const.
Key Takeaways
Use std::get with a compile-time index to access tuple elements by position.
Use std::get with a type only if that type appears once in the tuple.
Always include header to use std::tuple and std::get.
Accessed tuple elements can be read or modified via std::get.
Avoid out-of-range indices and ambiguous types to prevent compile errors.