Cover Image for Returning Multiple Values from a Function using Tuple and Pair in C++
150 views

Returning Multiple Values from a Function using Tuple and Pair in C++

The C++ return multiple values from a function using various techniques, including tuples and pairs from the <tuple> and <utility> headers, respectively. These mechanisms allow you to package multiple values together and return them as a single object. Here’s how to use tuples and pairs to return multiple values:

Using Tuples:

C++
#include <iostream>
#include <tuple>

// Function that returns multiple values using a tuple
std::tuple<int, double, std::string> getMultipleValues() {
    int intValue = 42;
    double doubleValue = 3.14159265359;
    std::string stringValue = "Hello, World";

    return std::make_tuple(intValue, doubleValue, stringValue);
}

int main() {
    auto result = getMultipleValues();

    int intValue;
    double doubleValue;
    std::string stringValue;

    std::tie(intValue, doubleValue, stringValue) = result;

    std::cout << "Int Value: " << intValue << std::endl;
    std::cout << "Double Value: " << doubleValue << std::endl;
    std::cout << "String Value: " << stringValue << std::endl;

    return 0;
}

In this example, the getMultipleValues function returns a tuple containing an integer, a double, and a string. In the main function, we use std::tie to unpack the values from the returned tuple.

Using Pairs:

C++
#include <iostream>
#include <utility>

// Function that returns two values using a pair
std::pair<int, double> getTwoValues() {
    int intValue = 42;
    double doubleValue = 3.14159265359;

    return std::make_pair(intValue, doubleValue);
}

int main() {
    auto result = getTwoValues();

    int intValue = result.first;
    double doubleValue = result.second;

    std::cout << "Int Value: " << intValue << std::endl;
    std::cout << "Double Value: " << doubleValue << std::endl;

    return 0;
}

In this example, the getTwoValues function returns a pair containing an integer and a double. We access the values using the first and second members of the returned pair.

Both tuples and pairs are versatile and can be used to return multiple values from a function when you need to package them together. However, if you need to return more than two or three values, using a tuple is generally more convenient and maintainable. Additionally, tuples provide a way to give names to the values returned, making the code more self-documenting.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS