Ort*_*x92 0 c++ matrix sparse-matrix c++11
我有一个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)
{
}
};
Run Code Online (Sandbox Code Playgroud)
这是如下初始化:
Matrix<double> M(5,5);
Run Code Online (Sandbox Code Playgroud)
创建一个5x5矩阵.
我想像这样为地图赋值:
M[{1,2}] = 1;
Run Code Online (Sandbox Code Playgroud)
我将如何以最易读的方式做到这一点?我不知道如何让下标和赋值运算符一起工作.
让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
};
Run Code Online (Sandbox Code Playgroud)