简体   繁体   中英

Sparse Matrix, overloading= c++

I need to overload = operator in my class SparseMatrix.

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;
  }
};

If I type mat(1,1) = 5 , program make a new element with parameters x=1 , y=1 , val=1 and push back this element in vector diff.

Seeing as you want to use this overloaded operator= in an expression like mat(1,1) = 5 and not mat = something , you don't really want to overload the operator= for the matrix itself. Instead, make operator() return a proxy for which you will overload the 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);
  }
};

You can play around with const correctness, perfect forwarding, making Proxy noncopyable etc., but the basic idea is outlined above.

actually you only need to update the overloading function for ()

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM