我的程序在 return 语句中引发“vector 下标超出范围”异常(编辑:断言)。嗯,看起来是这样,因为它恰好在该断点处引发了它。
这是导致它的函数:
Matrix4 Perspective(float fov, float aspect, float near, float far) const {
double yScale = 1.0 / tan(TO_RADIANS * fov / 2);
double xScale = yScale / aspect;
double depth = near - far;
Matrix4 perspective;
perspective[0][0] = xScale;
perspective[1][1] = yScale;
perspective[2][2] = (far + near) / depth;
perspective[2][3] = 2 * far * near / depth;
perspective[3][2] = -1;
perspective[3][3] = 0;
return perspective; // Raises exception here?
}
我的默认 Matrix4
构造函数很好,它基本上是这样做的:
_matrix.resize(4);
for (unsigned int i = 0; i < 4; ++i)
_matrix[i].resize(4);
_matrix
作为std::vector<std::vector<float>>
属性。所以一切都设置为 0。
最后,使用返回语句结果的代码是这样的:
Matrix4 camera = Perspective(70, 1, 0.2, 10);
我还有一个看起来也不错的复制构造函数:
Matrix4(const Matrix4& matrix) {
_matrix.reserve(4);
for (unsigned int i = 0; i < 4; ++i) {
_matrix[i].reserve(4);
for (unsigned int j = 0; j < 4; ++j)
_matrix[i][j] = matrix[i][j];
}
}
(我也有一个重载的 operator[] 但问题确实不能由它引起。)
exception 断言似乎是在 return perspective;
上提出的,但也许它是由调用该方法的代码行引起的,而复制构造函数不知何故无法复制?但在那种情况下,Visual Studio 应该将我带到构造函数中,因为我正在使用详细的逐步...
此时我迷路了......
最佳答案
在你的复制构造函数中,改变这个:
_matrix.reserve(4);
为此:
_matrix.resize(4);
因为你想用 vector::resize
实际分配空间,以便 _matrix[i][j] = matrix[i][j];
顺利工作。 vector::reserve
设置 vector 的容量。
阅读更多 vector resize VS reverse .
关于c++ - "Vector subscript out of range",在返回语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48425459/