Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 equivalent of python's x, y, z = array

Tags:

c++

c++11

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?

like image 896
user Avatar asked Nov 09 '12 02:11

user


1 Answers

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;
}
like image 85
jogojapan Avatar answered Oct 28 '22 08:10

jogojapan