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

标签 c++ c++11

是否有 C++11 等效于此 python 语句:

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 中是否有更紧凑的方法来完成此操作?

最佳答案

为此,您可以使用 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;
}

关于C++11 相当于 python 的 x, y, z = array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13301370/

相关文章:

c++ - 当 std::string 足以在 C++ 中初始化字符串时,为什么我们需要包含 <string> 头文件?

c++ - 在原始循环上使用 boost::irange 的性能损失

c++ - 在 OpenCV C++ 中打印出(Mat)矩阵的值

c++ - 释放属性对单例类的内存

c++ - 为什么 Xbox Controller 没有响应?

c++ - 为什么 for 循环中的 async 不能提高执行时间?

c++ - 自定义分配器兼容性

c++ - 如何显示链表(双向链表)的遍历?

c++ - 使用 STL 按成员(member)订购容器

c++ - 连接c++服务器时,flash socket发送错误数据