C ++ std :: map set和get using operator []

时间:2017-05-12 10:56:33

标签: operator-overloading c++14 sparse-matrix stdmap

我正在尝试使用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而不将其添加到地图中。

2 个答案:

答案 0 :(得分:0)

std::map::find方法。它返回一个迭代器,如果它等于map.end(),则表示该元素在地图中不存在。

答案 1 :(得分:0)

是的,这是背后的痛苦。幸运的是,聪明的C ++ 11 bods意识到了这一点并给了我们一个新的方法:at

使用at方法(从C ++ 11标准开始),虽然你仍然需要一个可能的std::out_of_range异常的catch处理程序,但它不会进行任何插入。

请参阅http://en.cppreference.com/w/cpp/container/map/at