Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of data-member in read-only structure, class in STL set

Tags:

c++

stl

The minimal example of the problem I'm having is reproduced below:

#include <set>
using namespace std;

class foo {
public:
  int value, x;
  foo(const int & in_v) {
   value = in_v;
   x = 0;
  }
  bool operator<(const foo & rhs) const {
   return value < rhs.value; 
 }
};

int main() {
  foo y(3);
  set<foo> F;
  F.insert(y);

  // Now try to modify a member of the set
  F.begin()->x=1;
  return 0;
}

With the error error: assignment of data-member ‘foo::value’ in read-only structure. I feel like I'm missing something simple here, but why am I unable to modify the member x in my class?

like image 716
Hooked Avatar asked Sep 23 '10 04:09

Hooked


1 Answers

Objects in a set are immutable; if you want to modify an object, you need to:

  1. make a copy of the object from the set,
  2. modify the copy,
  3. remove the original object from the set, and
  4. insert the copy into the set

It will look something like this:

std::set<int> s;
s.insert(1);

int x = *s.begin(); // (1)
x+= 1;              // (2)
s.erase(s.begin()); // (3)
s.insert(x);        // (4)
like image 158
James McNellis Avatar answered Sep 30 '22 00:09

James McNellis