C++ 11相当于python的x,y,z = array

use*_*ser 10 c++ c++11

是否存在与此python语句等效的C++ 11:

x, y, z = three_value_array
Run Code Online (Sandbox Code Playgroud)

在C++中,你可以这样做:

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];
Run Code Online (Sandbox Code Playgroud)

在C++ 11中有更简洁的方法来实现这一点吗?

jog*_*pan 11

您可以使用std::tuplestd::tie为此目的:

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • @Jason:不,但是可以编写一个函数`tuple_from_array`,它将给出:`std :: tie(x,y,z)= tuple_from_array(arr);`.留给读者练习.;) (2认同)