由于某种原因,我正在迭代一个类的元素,std::set并希望稍微修改键,知道订单将保持不变.
迭代器std::set是const_iterators因为如果修改了密钥,则可能导致订单错误,从而导致设置损坏.但是我确信我的操作不会改变集合中元素的顺序.
目前,这是我的解决方案:
class Foo
{
public:
Foo(int a, int b): a_(a),b_(b) {}
~Foo(){}
bool operator < (const Foo& o) const { return this.a_ < o.a_ ; }
void incrementB() const { ++b_; } // <-- the problem: it is not const!
private:
const int a_;
mutable int b_; // <-- I would like to avoid this
}
void f()
{
std::set<Foo> s;
// loop and insert many (distinct on a_) Foo elements;
std::for_each(s.begin(), …Run Code Online (Sandbox Code Playgroud)