简体   繁体   English

重载 operator[] 不断抛出运行时错误

[英]Overloading operator[] keeps throwing a runtime error

Alright, so I'm trying to create a Matrix class, and I really, really, want to be able to call elements by using brackets.好吧,所以我正在尝试创建一个 Matrix 类,我真的,真的,希望能够通过使用括号调用元素。 In the style of mMatrix[x][y].以 mMatrix[x][y] 的风格。

So I have a vector<vector<T>> member, and when overloading the [] operator, I return a reference to a vector<T> object.所以我有一个vector<vector<T>>成员,当重载 [] 运算符时,我返回对vector<T>对象的引用。

template<class T>
class Matrix
{
private:
    uint32_t DimensionHorizontal;
    uint32_t DimensionVertical;

    std::vector<std::vector<T>> matrix;

public:
    Matrix()
    {
        DimensionHorizontal = 10;
        DimensionVertical = 10;
    }

    std::vector<T>& operator[] (int index)
    {
        return matrix.[index];

    }

    Matrix(int x, int y)
    {
        DimensionHorizontal = x;
        DimensionVertical = y;
    }
};

This seems to be working because when I create a Matrix object, and try to add an element by doing Matrix[a][n] (using integers in this case), it compiles without issues.这似乎可行,因为当我创建一个 Matrix 对象,并尝试通过执行 Matrix[a][n](在本例中使用整数)添加一个元素时,它编译没有问题。 I later try to print out the value stored there with cout.我后来尝试用 cout 打印出存储在那里的值。

During runtime, I get the following error在运行时,我收到以下错误

Expression: vector subscript out of range on Line 1455 of the vector.表达式:向量第 1455 行的向量下标超出范围。 On line 1455:在第 1455 行:

_NODISCARD size_type capacity() const noexcept { // return current length of allocated storage
        auto& _My_data = _Mypair._Myval2;
        return static_cast<size_type>(_My_data._Myend - _My_data._Myfirst);
    }

    _NODISCARD _Ty& operator[](const size_type _Pos) noexcept { // strengthened
        auto& _My_data = _Mypair._Myval2;
#if _CONTAINER_DEBUG_LEVEL > 0
        _STL_VERIFY(
            _Pos < static_cast<size_type>(_My_data._Mylast - _My_data._Myfirst), "vector subscript out of range");
#endif // _CONTAINER_DEBUG_LEVEL > 0

        return _My_data._Myfirst[_Pos];
    }

I am sort of confused about why this is happening.我对为什么会这样感到困惑。 I know I'm trying to access something out of bounds, or doing something otherwise illegal, but Matrix[] should return a vector, and I should be able to use [] again to access the element T (in this case int), any help would be appreciated.我知道我正在尝试越界访问某些东西,或者做一些非法的事情,但是 Matrix[] 应该返回一个向量,我应该能够再次使用 [] 来访问元素 T(在本例中为 int),任何帮助,将不胜感激。

EDIT:编辑:

This is how I use the class这就是我使用课程的方式

int main()
{
    Matrix<int> a(10, 10);
    a[0][0] = 10;
    std::cout << a[0][0];
    return 0;
}

You need to resize the matrix in your constructor to match the size passed as arguments.您需要在构造函数中调整矩阵的大小以匹配作为参数传递的大小。

 Matrix(int x, int y) : matrix(x)
 {
    for( auto& sub : matrix ) {
       sub.resize(y);
    }
    DimensionHorizontal = x;
    DimensionVertical = y;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM