4

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.

Jon Bovi
  • 53
  • 9

1 Answers1

3

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);
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 2
    I would also mention using `std::tie` as: `node* n; int score; std::tie(n, score) = tuplefunct(abc);`, which does not introduce the auxiliary variable `x` before C++17. – Daniel Langr Dec 07 '18 at 12:28
  • @DanielLangr I have to admit, I answered merely by reading the documentation, my experience with tuples is rather low, thanks for the tip – 463035818_is_not_an_ai Dec 07 '18 at 12:30
  • auto should work for my solution. But I am curious about the third solution. Can i use `std::tie(n,-score)` to store score as the negation of returned value? – Jon Bovi Dec 07 '18 at 12:36
  • @JonBovi interesting question, though `tie` merely creates a tuple of lvalue references that lets you assign to the actual variables. Like everything, it is possible somehow, but afaik not without some additional effort – 463035818_is_not_an_ai Dec 07 '18 at 13:22
  • @JonBoiv Not with `std::tie`. It creates non-const lvalue references, and you cannot bind a non-const lvalue reference to an rvalue (`-score`). – Daniel Langr Dec 07 '18 at 13:43