c++ - 稀疏矩阵,重载 [] c++

标签 c++

我需要在类稀疏矩阵中重载 [] 运算符。 此运算符必须像在 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/

相关文章:

c++ - std::unordered_map find() 操作在 GCC7 中不起作用

c++ - Qt 和英特尔实感入门

c++ - 在 win32 中连续串行写入,C++

c++ - DirectX Index Buffer 索引顺序

c++ - std::vector 超出最小堆范围:C++

c++ - 如何计算stm32l0的i2c时序

javascript - OpenCV Rect 约定——什么是 x、y、宽度、高度?

c++ - "new"无法创建数组?

c++ - 在代码片段 ":"中解释 C++ 中 "int i:2;"运算符的使用

C++直方图bin排序