c++ - 使用带下标运算符的赋值运算符为 std::map 赋值

标签 c++ c++11 matrix sparse-matrix

我有一个矩阵类

template <typename T>
class Matrix
{
public:
  const size_t rows;
  const size_t cols;
  const std::map<std::array<int, 2>, T> data;

  Matrix(int a, int b) : rows(a), cols(b)
  {
  }
};

初始化如下:

Matrix<double> M(5,5);

创建一个 5x5 矩阵。

我想像这样给 map 赋值:

M[{1,2}] = 1;

我将如何以最具可读性的方式来做到这一点?我不确定如何让下标和赋值运算符协同工作。

最佳答案

让我们在 Matrix 中添加一些辅助别名

template <typename T>
class Matrix
{   
    // rather than stoping people changing the members via const
    // make them private
    size_t rows;
    size_t cols;
    map_type data;
public:
    using key_type = std::array<size_t, 2>;
    using mapped_type = T;
    using map_type = std::map<key_type, mapped_type>;

    Matrix(size_t r, size_t c) : rows(r), cols(c) { }

    const T& operator [](key_type key) const { return data[key]; }
          T& operator [](key_type key)       { return data[key]; }

    // other operations as appropriate
};

关于c++ - 使用带下标运算符的赋值运算符为 std::map 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48446866/

相关文章:

c++ - 从 C++ 列表中删除项目

c++ - std::tuple_cat 替换失败

c++ - Matlab中调用C++函数,处理二维数组,指针的指针?

ruby - 如何从特定点获取对角线值?

C++ 将 RHEL4 32 位编写的应用程序迁移到 RHEL6 64 位

c++ - 为什么以下代码不调用 std::string 的移动构造函数?

c++ - 不同大小的数组

c++ - 我如何使用可变参数模板产生默认参数的效果

matrix - 哪些编码项目用于创造艺术和美感?

c++ - Qt C++ 在函数模板中使用约束