稀疏矩阵,重载= c ++

时间:2013-12-30 09:15:31

标签: c++

我需要在我的SparseMatrix类中重载= operator

template <class T>
class SparseMatrix
{

  public:
  template <class T>
  class element
  {
  public:
      int x;
      int y;
      T val; 
      element(T war, int x1, int y1) { val = war; x = x1; y = y1; };
   };

  vector<element<T>> diff; //contains a cell with diffrent value
  T value; //contains a value of all cells at begining.
  int sizeX;
  int sizeY;

  SparseMatrix(T val, int x, int y) { value = val; sizeX = x; sizeY = y; };
  ~SparseMatrix() {};

  T& operator()(int t, int t1)
  {
    for (int x = 0; x < diff.size(); x++)
    if (diff[x].x == t && diff[x].y == t1)
        return diff[x].val;
    return value;
  }
};

如果我输入mat(1,1) = 5,程序会创建一个包含参数x=1y=1val=1的新元素,并在向量差异中推回此元素。

2 个答案:

答案 0 :(得分:2)

看到您要在operator=而不是mat(1,1) = 5这样的表达式中使用此重载mat = something,您实际上并不想为矩阵重载operator=本身。相反,make operator()会返回一个代理,您将为其重载运算符:

template <class T>
class SparseMatrix
{

  //...

  struct Proxy
  {
    int t, t1;
    SparseMatrix &mat;

    Proxy(int t, int t1, SparseMatrix &mat) : t(t), t1(t1), mat(mat) {}

    operator T() const {
      for (int x = 0; x < mat.diff.size(); x++)
        if (mat.diff[x].x == t && mat.diff[x].y == t1)
          return mat.diff[x].val;
      return mat.value;
    }

    T& operator= (const T &v) {
      for (int x = 0; x < mat.diff.size(); x++)
        if (mat.diff[x].x == t && mat.diff[x].y == t1)
          return mat.diff[x].val = v;  //it exists, assign & return it
      // it doesn't exist, create new one
      mat.diff.push_back(element<T>(v, t, t1));
      return mat.diff.back().val;
    }
  };

  Proxy operator() (int t, int t1) {
    return Proxy(t, t1, *this);
  }
};

你可以使用const正确性,完美转发,Proxy不可复制等,但基本思路如上所述。

答案 1 :(得分:0)

实际上你只需要更新()

的重载函数
T& operator()(int t, int t1)
{
    for (size_t x = 0; x < diff.size(); x++)
    {
        if (diff[x].x == t && diff[x].y == t1)
            return diff[x].val;
    }

    diff.push_back(element(value,t,t1));
    return diff.back().val;
}