由于某种原因,我在std::set
中迭代了一个类的元素,并且想要稍微修改这些键,并知道该顺序将保持不变。我该如何改进这种强迫我声明一个成员函数const并声明变量可变的设计?
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(), c.end(), [](const Foo& s) { s.incrementB(); }); // Foo must be const. iterators are const_iterators
}
你将如何修改它(我知道我可以使用一个std::map
,但我很好奇,你是否可以建议其他选项),以去除可变和const?
感谢
你不想使用地图的具体原因是什么?是因为内存布局的原因(看分配器?)还是代码风格的原因? – sehe
@sehe:具体原因是我想知道在重构代码之前是否存在其他选项。我并不完全排除切换到地图。 – Benoit