2012-11-09 53 views
8

的是否有一個C++ 11相當於這條巨蟒聲明:C++ 11相同的python的X,Y,Z =陣列

x, y, z = three_value_array 

在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]; 

在C++ 11中有更緊湊的方式來完成這個嗎?

+2

不使用標準C++(Boost.Fusion可能有一些在這裏幫助),但是如果你有'的std ::組<雙,雙, double>'而不是'std :: array '然後你可以使用'std :: tie(x,y,z)= three_value_tuple;'代替。 – ildjarn

回答

9

您可以使用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; 
} 
+1

數組的原始構造會起作用嗎? – Jason

+0

不幸的是'std :: tie'被定義爲僅返回'std :: tuple'。 – jogojapan

+0

你可以做std :: tie(j1,j2,j3)= std :: make_tuple(ar [0],ar [這可能不像Python代碼那樣優雅。 – jogojapan

相關問題