简体   繁体   中英

Sparse Matrix, overloading [] c++

I need to overload [] operator in class Sparse Matrix. This operator must work like in 2D table access. For example tab[1][1], return reference.

The problem is I have a vector of elements(struct).

template <class T>
struct element
{
    int x;
    int y;
    T Value;
};

If I want to access some field, I must store 2 coordinates from operator. I don't know how to do it.

class ElementProxy
{
    Container* myOwner;
    int myRowIndex;
    int myColumnIndex;
public:
    ElementProxy( Container* owner, int rowIndex, int columnIndex )
        : myOwner( owner )
        , myRowIndex( rowIndex )
        , myColumnIndex( columnIndex )
    {
    }

    operator Type() const  //  lvalue to rvalue conversion
    {
        return myOwner->get( myRowIndex, myColumnIndex );
    }

    void operator=( Type const& rhs ) const
    {
        myOwner->set( myRowIndex, myColumnIndex, rhs );
    }
};

class RowProxy
{
public:
    RowProxy( Container* owner, int rowIndex )
        : myOwner( owner )
        , myRowIndex( rowIndex )
{
}
ElementProxy operator[]( int columnIndex ) const
{
    return ElementProxy( myOwner, myRowIndex, columnIndex );
}
};

要获得自然语法,请让矩阵类返回一个行对象,该对象也会重载[]运算符,然后返回该元素。

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