Language: EN

cpp-que-son-tuplas

What are tuples and how to use them in C++

In C++ a tuple is a data structure that allows grouping multiple values of different types into a single variable.

Unlike classes or structures (struct), tuples are simpler and designed to handle sets of data of different types without the need to define a new type.

Tuples in C++ are immutable, which means that once created, their values cannot be modified. This feature makes them ideal for representing groupings of data that do not need to change once defined.

Syntax of tuples

Tuples are defined and used through the std::tuple class from the C++ standard library.

#include <tuple>

std::tuple<type1, type2> tuple = std::make_tuple(value1, value2);
  • type1, type2: These are the data types of the elements of the tuple.
  • value1, value2: These are the values assigned to the elements of the tuple.

It is possible to create a tuple with any number of elements (although it is not advisable to make extremely long tuples to maintain code clarity)

#include <tuple>

std::tuple<int, std::string, double> myTuple = std::make_tuple(1, "Hello", 3.14);

Basic example

Let’s look at a simple example to define and use a tuple in C++:

#include <iostream>
#include <tuple>

int main() {
    std::tuple<int, std::string, double> myTuple = std::make_tuple(1, "Hello", 3.14);

    // Accessing elements
    int integer = std::get<0>(myTuple);
    std::string text = std::get<1>(myTuple);
    double number = std::get<2>(myTuple);

    std::cout << "Integer: " << integer << std::endl; // Prints "Integer: 1"
    std::cout << "Text: " << text << std::endl;       // Prints "Text: Hello"
    std::cout << "Number: " << number << std::endl;   // Prints "Number: 3.14"

    return 0;
}

Basic usage

Accessing tuple elements

To access the elements of a tuple, the function std::get<N>(tuple) is used, where N is the index of the element we want to obtain (starting from 0).

std::tuple<int, std::string, bool> tuple = std::make_tuple(1, "Hello", true);

int number = std::get<0>(tuple);   // Gets the first element
std::string text = std::get<1>(tuple); // Gets the second element
bool booleanValue = std::get<2>(tuple); // Gets the third element

Tuple destructuring

Although C++ does not have direct destructuring for tuples like other languages, you can use std::tie to decompose a tuple into separate variables.

#include <iostream>
#include <tuple>

int main() {
    std::tuple<int, std::string, double> tuple = std::make_tuple(1, "Hello", 3.14);

    int integer;
    std::string text;
    double number;

    std::tie(integer, text, number) = tuple;

    std::cout << "Integer: " << integer << std::endl;
    std::cout << "Text: " << text << std::endl;
    std::cout << "Number: " << number << std::endl;

    return 0;
}

Practical examples