std::tuple
- C++ course
- Advanced
- Lesson 11/83
- 5 min
Learn heterogeneous collections with std::tuple.
std::tuple
std::tuple is a template that holds N values of different types in one container. The syntax is std::tuple<int, double, std::string> t{42, 3.14, "hello"};. Each element may have a different type; this generalizes std::pair.
Elements are accessed with std::get<index>(t). The index must be known at compile time; it does not change at run time. std::tuple_size and std::tuple_element give size and type info. Tuples are common for returning multiple values from a function.
Access with std::get
std::get reads a tuple element by a compile-time index. std::get<0>(t) returns the first element, std::get<1>(t) the second. A type also works: std::get<int>(t) returns the int element of the tuple.
An out-of-range index errors at compile time. If the same type appears more than once, type-based access is ambiguous; use an index instead. Tuples can also be unpacked with structured bindings: auto [a, b] = t; binds each element to a separate variable.
Practice Build a tuple and print
Create std::tuple<int, double, std::string> t{42, 3.14, "hello"};. Read the first element with std::get<0>(t) and print it via std::cout. Remember to include <tuple>.
Starter code
#include <iostream>
#include <tuple>
#include <string>
int main() {
// Build a tuple and print the first element
return 0;
}Sample solution
#include <iostream>
#include <tuple>
#include <string>
int main() {
std::tuple<int, double, std::string> t{42, 3.14, "hello"};
std::cout << std::get<0>(t);
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the std::get line
std::tuple<int, double> t{42, 3.14};
auto x = ____;
std::tuple<int, double> t{42, 3.14};
auto x = std::get<0>(t);
Explanation: std::get<0>(t) returns the first element.
2 What does std::tuple hold?
- Only two values
- N values of the same type
- N values of different types Correct answer
- Only pointers
Explanation: std::tuple holds N values of different types.
3 Match each tool to its purpose
| Term | Meaning |
|---|---|
std::tuple<T1, T2> |
Heterogeneous container |
std::get<0>(t) |
Read first element |
std::tuple_size<t> |
Element count |
auto [a, b] = t |
Structured bindings |