简体   繁体   中英

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. In the style of 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.

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. I later try to print out the value stored there with cout.

During runtime, I get the following error

Expression: vector subscript out of range on Line 1455 of the vector. On line 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.

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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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