c++ - "Vector subscript out of range",在返回语句?

标签 c++ vector outofrangeexception

我的程序在 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/

相关文章:

c++ - 无法附加到使用 Visual Studio 2005 创建的进程

c++ - vector 的 undefined reference

c++ - for 循环的问题(初学者)

c++ - 如何检查 std::vector 超出范围的访问

c++ - 对于已定义的符号,静态库链接问题 "Undefined symbols"

c++ - 在 C++、结构或类中应该使用什么来创建链接列表

c++ - 将一个函数的 vector + map 版本合并为一个兼容的版本

asp.net - 从 Sql Server 2008 在 TreeView 中添加父节点和子节点

javascript - 未捕获的范围错误: Item index is out of range error in WebSQL Query Results

c++ - Rcpp:在不导出 C++ 函数的情况下在 R 中调用 C++ 函数