Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sparse Matrix, overloading [] c++

Tags:

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.

like image 513
Xwar Avatar asked Mar 22 '26 15:03

Xwar


1 Answers

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 );
}
};
like image 158
Yanshof Avatar answered Mar 25 '26 06:03

Yanshof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!