我需要在类稀疏矩阵中重载 [] 运算符。 此运算符必须像在 2D 表访问中一样工作。 例如 tab[1][1],返回引用。
问题是我有一个元素 vector (结构)。
template <class T>
struct element
{
int x;
int y;
T Value;
};
如果我想访问某个字段,我必须存储来自运算符(operator)的 2 个坐标。 我不知道该怎么做。
最佳答案
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 );
}
};
关于c++ - 稀疏矩阵,重载 [] c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824282/