Jaskamal Kainth

Tuples in C++

std::tuple is a template class in C++ that can hold a fixed-size collection of elements of different types.

Basic Usage

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

int main() {
    // Creating a tuple
    std::tuple<int, std::string, double> person(30, "John", 6.1);
    
    // Accessing elements using std::get
    std::cout << "Age: " << std::get<0>(person) << std::endl;
    std::cout << "Name: " << std::get<1>(person) << std::endl;
    std::cout << "Height: " << std::get<2>(person) << std::endl;
    
    // C++17 structured binding
    auto [age, name, height] = person;
    std::cout << "Name: " << name << std::endl;
    
    return 0;
}

Tuple Operations

Creating Tuples

// Using make_tuple helper
auto person = std::make_tuple(30, "John", 6.1);

// C++17 class template argument deduction
std::tuple person2(30, "John", 6.1);

Tuple Concatenation

// C++14 and later
auto tuple1 = std::make_tuple(1, 'a');
auto tuple2 = std::make_tuple("hello", 5.5);
auto combined = std::tuple_cat(tuple1, tuple2); // tuple<int, char, const char*, double>

Tuples are especially useful when you need to return multiple values from a function or when you need to group heterogeneous data without defining a custom class.