我正在尝试使用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];
}
};
使用这个类可以创建一个新对象并设置元素,但是,[] -operator也用于获取元素,例如:
std::cout << M[{1,1}] << std::endl;
这个问题是如果用于获取一个尚未设置的元素,它会在地图中创建一个具有给定索引和值0的新部分,这对于稀疏矩阵类是不希望的,因为地图应该只包含非零元素。
通过区分'setting'和'getting',可以通过[] -operator解决这个问题吗?在“获取”的情况下,操作员只返回0而不将其添加到地图中。
答案 0 :(得分:0)
有std::map::find
方法。它返回一个迭代器,如果它等于map.end()
,则表示该元素在地图中不存在。
答案 1 :(得分:0)
at
。
使用at
方法(从C ++ 11标准开始),虽然你仍然需要一个可能的std::out_of_range
异常的catch处理程序,但它不会进行任何插入。