Search code examples
c++recursionreturntuples

Storing 2 variables at once from a tuple function


I have a tuple function that returns a tuple of the form

<node*,int>

Is there a way to store 2 values at once without creating another tuple. I know we can do

n,score=tuplefunct(abc);

in python. But if I want to store both return values in c++ without making another tuple i need to call twice

n=get<0>(tuplefunct(abc);
score=get<1>(tuplefunct(abc));

is there any alternative to this in c++ to store the values at once.


Solution

  • You dont need to call the function twice (note that there is no "another tuple" involved, the function returns one and thats what you use):

    auto x = tuplefunct(abc);
    auto n = get<0>(x);
    auto score = get<1>(x);
    

    If you have C++17 available you can use structured bindings

    auto [n,score] = tuplefunct(abc);
    

    Or to get close to that without C++17, you can use std::tie (from C++11 on):

    node* n;
    int score;
    std::tie(n,score) = tuplefunct(abc);