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

前端 未结 3 506
遇见更好的自我
遇见更好的自我 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:55

    Given that the "x" variable is not involved in the less-than comparison, it would be safe in this case to make "x" mutable, allowing you to modify it from within the set. Your class definition would then become:

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

    And you can now use it in the std::set and modify x as you like. In this case it is pointless to keep two copies of the data structure as the previous poster has suggested.

提交回复
热议问题