What is Tuple in C++: Explanation and Example
tuple is a fixed-size collection that can hold elements of different types together. It is like a box that stores multiple values, each possibly of a different type, accessible by position. Tuples are defined in the <tuple> header and help group related data without creating a custom struct or class.How It Works
Think of a tuple as a small container that holds a few items, where each item can be a different type. For example, you can store a number, a word, and a true/false value all in one tuple. Unlike arrays that hold many items of the same type, tuples mix types.
Each element in a tuple is accessed by its position, starting from zero. You can imagine it like a row of boxes labeled 0, 1, 2, and so on, where each box holds a different kind of thing. This makes tuples useful when you want to group different pieces of data together temporarily without making a new structure.
Example
This example shows how to create a tuple with an integer, a string, and a double, then access and print each value.
#include <iostream> #include <tuple> #include <string> int main() { std::tuple<int, std::string, double> person(30, "Alice", 65.5); std::cout << "Age: " << std::get<0>(person) << "\n"; std::cout << "Name: " << std::get<1>(person) << "\n"; std::cout << "Weight: " << std::get<2>(person) << "\n"; return 0; }
When to Use
Use tuples when you want to group a few related values of different types quickly without creating a new class or struct. They are handy for returning multiple values from a function or passing a small set of mixed data around your program.
For example, if a function needs to return a person's ID, name, and score, a tuple can hold all three together. Tuples keep your code simple and avoid extra boilerplate when you don't need a full custom type.
Key Points
- Tuples can hold multiple values of different types in one object.
- Elements are accessed by their position using
std::get<index>. - Tuples are fixed size and defined at compile time.
- They are useful for grouping data without creating new types.