【发布时间】:2017-05-12 10:56:32
【问题描述】:
我正在尝试使用 std::map 构建一个 2D 稀疏矩阵类,它应该以(例如)以下方式调用:
SparseMatrix<double> M(2,2); // Create a new sparse matrix with 2 rows and 2 columns
M[{1,1}] = 3.1; // Sets element {1,1} to 3.1
以下类可以执行这些任务:
template < typename T >
class SparseMatrix
{
std::map< array<int, 2>, T> data;
const array<int, 2> size;
public:
SparseMatrix(const int rows, const int cols)
: size({ rows, cols }) {}
// []-operator to set and get values from matrix
T& operator[](const array< int,2 > indices)
{
// Check if given indices are within the size of the matrix
if(indices[0] >= size[0] || indices[1] >= size[1])
throw invalid_argument("Indices out of bounds");
return data[indices];
}
};
使用这个类可以创建一个新对象并设置元素,但是,[]-操作符也用于获取元素,例如:
std::cout << M[{1,1}] << std::endl;
这样做的问题是,如果它用于获取尚未设置的元素,它会在地图中创建一个具有给定索引和值 0 的新部分,这对于稀疏矩阵类来说是不希望的,因为地图应该只包含非零元素。
是否可以通过区分“设置”和“获取”来使用 [] 运算符来解决这个问题?在“获取”的情况下,操作员是否应该只返回一个 0 而不会将其添加到地图中。
【问题讨论】:
-
函数/操作符不知道使用的上下文(set/get)。您可以返回带有
overload =和operator const T& ()的包装器。 (但不处理M[{1,1}].setInternal(/*..*/))。 -
顺便说一句,你如何处理
M[{1,1}] = 0;? -
@Jarod42 关于
M[{1,1}] = 0;的好消息,我应该对此进行另一次检查,因为它也不应该存储在地图中。
标签: operator-overloading c++14 sparse-matrix stdmap