-1

I tried to have a struct with copy assignment, but it gave me some error.

struct Data {
  unsigned short xx;
  unsigned short yy;
  std::map<int, vector<int>> map;
  bool operator<(....& rhs) const 
  {
      ......
  }

   bool operator==(....& rhs) const 
   {
    return xx == rhs.xx && yy == rhs.yy;
  }


  Data& operator=(const Data& rhs) {
    if (this != &rhs) {
      xx = rhs.xx;
      yy = rhs.yy;
      for (int i = 0; i < 20; i++){
        vector<int> temp;
        vector<int> tempC = rhs.map[i];
        for (int j = 0; j < tempC.size(); j++){
            temp.push_back(tempC[j]);
        }
        map[i] = temp;
      }
    } 
    return *this;
} 


}; 

Error message:

Error: passing 'const std::map<int, std::vector<int> >' as 'this' argument discards qualifiers [-fpermissive]

so what is wrong?

user4581301
  • 33,082
  • 7
  • 33
  • 54
Keith
  • 53
  • 1
  • 2
  • 8
  • 1
    Doesn't solve your problem directly, but [What is the copy-and-swap idiom?](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) may be of use to you. – user4581301 Apr 09 '19 at 21:46

1 Answers1

3

The offending line is

vector<int> tempC = rhs.map[i];

The issue: std::map::operator[] is non-const because it inserts a value if none exists for the given key. But your rhs is const. You need to use find instead of [].

The entire loop is also completely unnecessary since std::map has a copy assignment operator, and so does std::vector. So you can in fact just assign member-wise. Or, better yet, do as suggested in the comments, and implement the copy-and-swap idiom.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    Based on the member variables shown, the odds are good that the asker can invoke the [Rule of Zero](https://en.cppreference.com/w/cpp/language/rule_of_three) and leave everything up to the compiler. – user4581301 Apr 09 '19 at 22:01