10

Is there a C++11 equivalent to this python statement:

x, y, z = three_value_array

In C++ you could do this as:

double x, y, z;
std::array<double, 3> three_value_array;
// assign values to three_value_array
x = three_value_array[0];
y = three_value_array[1];
z = three_value_array[2];

Is there a more compact way of accomplishing this in C++11?

user
  • 7,123
  • 7
  • 48
  • 90
  • 2
    Not with standard C++ (Boost.Fusion may have something to assist here), but if you had `std::tuple` rather than `std::array` then you could use `std::tie(x, y, z) = three_value_tuple;` instead. – ildjarn Nov 09 '12 at 02:48

1 Answers1

11

You can use std::tuple and std::tie for this purpose:

#include <iostream>
#include <tuple>

int main()
{
  /* This is the three-value-array: */
  std::tuple<int,double,int> triple { 4, 2.3, 8 };

  int i1,i2;
  double d;

  /* This is what corresponds to x,y,z = three_value_array: */
  std::tie(i1,d,i2) = triple;

  /* Confirm that it worked: */    
  std::cout << i1 << ", " << d << ", " << i2 << std::endl;

  return 0;
}
jogojapan
  • 68,383
  • 11
  • 101
  • 131
  • `std::tie` is defined to return `std::tuple` only, unfortunately. – jogojapan Nov 09 '12 at 02:51
  • You could do `std::tie(j1,j2,j3) = std::make_tuple(ar[0],ar[1],ar[2]);` (where `ar` is the array), but this is probably not quite as elegant as the Python code. – jogojapan Nov 09 '12 at 02:55
  • 2
    @Jason: No, but it's possible to write a function `tuple_from_array` that would give: `std::tie(x, y, z) = tuple_from_array(arr);`. Left as an exercise for the reader. ;) – GManNickG Nov 09 '12 at 02:56
  • That's what I was just thinking @GManNickG, but using an iterator as the argument and template argument for the tuple size if needed. – Jason Nov 09 '12 at 02:57
  • 1
    Luckily, we have this oldie but goodie: http://stackoverflow.com/questions/10604794/convert-stdtuple-to-stdarray-c11 – user Nov 09 '12 at 03:01