【问题标题】:C++ std::map set and get using operator[]C++ std::map 使用 operator[] 设置和获取
【发布时间】: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&amp; () 的包装器。 (但不处理M[{1,1}].setInternal(/*..*/))。
  • 顺便说一句,你如何处理M[{1,1}] = 0;?
  • @Jarod42 关于M[{1,1}] = 0; 的好消息,我应该对此进行另一次检查,因为它也不应该存储在地图中。

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


【解决方案1】:

您可以使用代理而不是T&amp; 来区分读取和写入。只显示相关代码:

template <typename T>
class SparseMatrixProxy {
    public:
    //for reading an element:
    operator T() const {
        // Check if given indices are within the size of the matrix
        if (indices[0] >= matrix.size[0] || indices[1] >= matrix.size[1])
            throw std::invalid_argument("Indices out of bounds");
        auto map_it = matrix.data.find(indices);
        if (map_it == matrix.data.end()) {
            return T{};
        }
        return map_it->second;
    }
    //for writing an element:
    auto operator=(const T &t) {
        //optional: when setting a value to 0 erase it from the map
        if (t == T{}) {
            matrix.data.erase(indices);
        } else {
            matrix.data[indices] = t;
        }
        return *this;
    }
};

像这样在SparseMatrix中使用:

// []-operator to set and get values from matrix
SparseMatrixProxy<T> operator[](const std::array<int, 2> indices) {
    return {*this, indices};
}

有用法:

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
std::cout << M[{{1, 1}}] << '\n';
assert(M.mapsize() == 1); //1 element for index {1,1}
std::cout << M[{{0, 0}}] << '\n';
assert(M.mapsize() == 1); //still 1 element because reading doesn't insert an element
M[{{1, 1}}] = 0;
assert(M.mapsize() == 0); //0 elements because we set the only non-0 element to 0

Completeexample.

【讨论】:

  • 谢谢!这似乎完成了我所要求的一切,太棒了!我现在正试图弄清楚是否有可能消除对双花括号的需求。
  • @Merel 双花括号不是必需的,我的编译器只是警告我:“建议在子对象初始化时使用大括号 [-Wmissing-braces]”。
【解决方案2】:

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

【讨论】:

  • 但是后来还是不知道是get还是set。设置元素的时候可以不存在也可以存在,获取的时候不能不存在。
【解决方案3】:

是的,后背很痛。幸运的是,聪明的 C++11 开发人员意识到了这一点,并为我们提供了一种新方法:at。

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

见http://en.cppreference.com/w/cpp/container/map/at

【讨论】:

  • 无论如何,您都可以在 C++11 之前使用find 方法执行此操作(不进行范围检查,但是...)
  • 是的,但是find 不是很清楚。我一直在回答以 C++11 为基准的问题。
  • 我查看了at-方法,但是在“设置”时,我们确实想要向地图添加一个元素,即使它会引发异常。 at-方法仍然没有区分设置和获取,对吧?
  • 从这个意义上说不是。对于at 的非const 版本,您会得到一个非const 引用,仅此而已。对于您的具体用法,我建议您编写自己的存根函数。
【解决方案4】:

从性能的角度来看,通过创建自己的映射来实现稀疏矩阵更便宜,例如通过存储索引。

template<typename T>
class SparseMatrix
{
...
int m, n;
vector<T> values;
vector<int> cols;
vector<int> rows;
}

template<typename T> 
T SparseMatrix<T>::get(int row, int col) const 
 { 
    this->validateCoordinates(row, col); 


    int currCol = 0; 


    for (int pos = rows.at(row - 1) - 1; pos < rows.at(row) - 1; pos++) 
             { 
        currCol = cols.at(pos); 

        if (currCol == col) 
                    return vals.at(pos); 
         else if (currCol > col)  
            break; 
    } 


    return T(); 
 }

 template<typename T> 
SparseMatrix<T> & SparseMatrix<T>::set(T val, int row, int col) 
{ 
    // Validate coordinates here?

    int pos = rows.at(row - 1) - 1; 
    int currCol = 0; 


    for (; pos < rows.at(row) - 1; pos++) { 
        currCol = cols.at(pos); 


        if (currCol >= col) { 
            break; 
        } 
    } 


    if (currCol != col) { 
        if (!(val == T())) { 
            this->insert(pos, row, col, val); 
        } 


    } else if (val == T()) { 
        this->remove(pos, row); 


    } else { 
        vals.at(pos) = val; 
    } 


    return *this; 
 } 


template<typename T> 
void SparseMatrix<T>::insert(int index, int row, int col, T val) 
{ 

    vals.insert(vals.begin() + index, val); 
    cols.insert(cols.begin() + index, col); 

    for (int i = row; i <= this->m; i++)  
        rows.at(i) = rows.at(i) + 1; 

 } 

等等……

【讨论】:

    猜你喜欢
    • 2017-02-27
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2022-08-24
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多