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

前端 未结 3 519
遇见更好的自我
遇见更好的自我 2021-02-14 19:09

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

#include 
using namespace std;

class foo {
public:
  int value, x;
  foo(const in         


        
3条回答
  •  后悔当初
    2021-02-14 19:42

    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 s;
    s.insert(1);
    
    int x = *s.begin(); // (1)
    x+= 1;              // (2)
    s.erase(s.begin()); // (3)
    s.insert(x);        // (4)
    

提交回复
热议问题