繁体   English   中英

使用赋值运算符和下标运算符将值分配给std :: map

[英]Use assignment operator with subscript operator to assign value to std::map

我有一个矩阵课

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矩阵。

我想像这样为地图分配值:

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
};

您必须提供成员:

const T& operator [](std::pair<std::size_t, std::size_t>) const;
      T& operator [](std::pair<std::size_t, std::size_t>);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM