我是新手,遇到 C++ 方面的问题。我正在创建 3D 坐标(x、y 和 z 用于面的每个角,然后是 6 个面)并收到许多错误。这是我的代码:
#include <vector>
int main()
{
std::vector<int> xyzCoords = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
int x1 = 0;
int y1 = 1;
int z1 = 2;
int x2 = 3;
int y2 = 4;
int z2 = 5;
xyzCoords = {
{ x1, y1, z1, x2, y1, z1, x2, y1, z2, x1, y1, z2 },
{ x1, y2, z1, x2, y2, z1, x2, y2, z2, x1, y2, z2 },
{ x1, y2, z1, x1, y1, z1, x1, y1, z2, x1, y2, z2 },
{ x2, y2, z1, x2, y1, z1, x2, y1, z2, x2, y2, z2 },
{ x1, y2, z2, x1, y1, z2, x2, y1, z2, x2, y2, z2 },
{ x1, y2, z1, x1, y1, z1, x2, y1, z1, x2, y2, z1 }
};
return 0;
}
这是出现问题的代码。你可以看到我将 xyzCoords
定义为 vector 。我不确定这是否是正确的方法。我也不想单独定义 xyz123
。实现这一目标的最佳方法是什么?我应该使用列表、数组还是 vector ?请编写有关如何执行此操作的代码。谢谢!
错误:
E0289: no instance of constructor "std::vector<_Ty, _Alloc>::vector [with _Ty=int, _Alloc=std::allocator]" matches the argument list
E0349: no operator "=" matches these operands
C2440: 'initializing': cannot convert from 'initializer list' to 'std::vector>'
C2679: binary '=': no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion)
最佳答案
您的初始化与您声明的类型不匹配。您声明了一个一维数组,而您的初始化是一个二维数组。
std::vector<int> xyzCoords = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
应该是:
std::vector<std::vector<int>> xyzCoords = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
你提到了 xyz
坐标,那你为什么不做一个专门用于坐标的类,例如:
struct Point {
int x, y, z;
};
无论如何,我不建议您使用天真的方法来解决这个问题,因为这将是一个矩阵运算密集型计算。你应该使用 BLAS/LAPACK图书馆或它的包装器,如 Eigen或 Armadillo .他们肯定快得多。
关于c++ - 无法从 "initializer list"转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47896455/