0
0
CppHow-ToBeginner · 3 min read

How to Use Tuple in C++: Syntax and Examples

In C++, use std::tuple to store multiple values of different types in a single object. You create a tuple with std::make_tuple or by directly specifying types, and access elements using std::get<index>().
📐

Syntax

A std::tuple groups multiple values of different types into one object. You declare it by specifying the types inside angle brackets. Use std::make_tuple to create a tuple without explicitly writing types. Access elements by their zero-based index with std::get<index>().

cpp
#include <tuple>
#include <string>

// Declare a tuple type holding int, double, and string
std::tuple<int, double, std::string> myTuple;

// Create a tuple using make_tuple
auto t = std::make_tuple(10, 3.14, "hello");

// Access elements
int i = std::get<0>(t);       // 10
double d = std::get<1>(t);    // 3.14
std::string s = std::get<2>(t); // "hello";
💻

Example

This example shows how to create a tuple with different types, access its elements, and print them.

cpp
#include <iostream>
#include <tuple>
#include <string>

int main() {
    // Create a tuple with int, double, and string
    std::tuple<int, double, std::string> person = std::make_tuple(25, 72.5, "Alice");

    // Access and print each element
    std::cout << "Age: " << std::get<0>(person) << "\n";
    std::cout << "Weight: " << std::get<1>(person) << " kg\n";
    std::cout << "Name: " << std::get<2>(person) << "\n";

    return 0;
}
Output
Age: 25 Weight: 72.5 kg Name: Alice
⚠️

Common Pitfalls

Common mistakes include:

  • Accessing tuple elements with an invalid index causes a compile error.
  • Trying to modify tuple elements without using std::get<index>() correctly.
  • Confusing tuple with pair (tuple can hold more than two elements).

Always use the correct index and type when accessing elements.

cpp
#include <tuple>
#include <iostream>

int main() {
    auto t = std::make_tuple(1, 2.5, "text");

    // Wrong: std::get<3>(t); // Error: index out of range

    // Correct:
    std::cout << std::get<0>(t) << "\n"; // prints 1

    return 0;
}
Output
1
📊

Quick Reference

OperationSyntaxDescription
Create tuplestd::tuple<T1, T2, ...> t;Declare a tuple with types T1, T2, etc.
Make tupleauto t = std::make_tuple(val1, val2, ...);Create tuple with values, types inferred
Access elementstd::get<index>(t)Get element at zero-based index
Modify elementstd::get<index>(t) = new_value;Change value at index
Get tuple sizestd::tuple_size<decltype(t)>::valueNumber of elements in tuple

Key Takeaways

Use std::tuple to store multiple values of different types together.
Create tuples with std::make_tuple or by specifying types explicitly.
Access elements by zero-based index using std::get<index>().
Ensure index is valid to avoid compile-time errors.
Tuples can hold any number of elements, unlike pairs which hold only two.