为什么std :: set <> :: find返回一个const?

Tho*_*mas 0 c++ stl const set

可能重复:
C++ STL集更新很繁琐:我无法更改元素

我想使用a std::set<>来计算某个值的出现次数并同时对对象进行排序.为此,我创建了一个类RadiusCounter

class RadiusCounter
{
public:
    RadiusCounter(const ullong& ir) : r(ir) { counter = 1ULL; }
    void inc() { ++counter; }
    ullong get() const { return counter;}
    ullong getR() const { return r;}
    virtual ~RadiusCounter();
protected:
private:
    ullong r;
    ullong counter;
};
Run Code Online (Sandbox Code Playgroud)

(析构函数不做任何操作)和比较运算符:

const inline bool operator==(const RadiusCounter& a, const RadiusCounter& b) {return  a.getR() == b.getR();}
const inline bool operator< (const RadiusCounter& a, const RadiusCounter& b) {return a.getR() < b.getR();}
const inline bool operator> (const RadiusCounter& a, const RadiusCounter& b) {return a.getR() > b.getR();}
const inline bool operator!=(const RadiusCounter& a, const RadiusCounter& b) {return a.getR() != b.getR();}
const inline bool operator<=(const RadiusCounter& a, const RadiusCounter& b) {return a.getR() <= b.getR();}
const inline bool operator>=(const RadiusCounter& a, const RadiusCounter& b) {return a.getR() >= b.getR();}
Run Code Online (Sandbox Code Playgroud)

现在我想像这样使用它:

set<RadiusCounter> theRadii;
....
ullong r = getSomeValue();

RadiusCounter ctr(r);
set<RadiusCounter>::iterator itr = theRadii.find(ctr);

// new value -> insert
if (itr == theRadii.end()) theRadii.insert(ctr);

// existing value -> increase counter
else itr->inc();
Run Code Online (Sandbox Code Playgroud)

但是现在编译器在线路上抱怨itr->inc():

error: passing 'const RadiusCounter' as 'this' argument of 'void RadiusCounter::inc()' discards qualifiers
Run Code Online (Sandbox Code Playgroud)

为什么*itrconst中的实例在这里?

Oli*_*rth 9

因为你不能修改一个元素std::set.如果可以,它将允许它破坏严格弱排序不变量的可能性,从而导致未定义的行为.

如果要修改元素,则应擦除元素,然后插入新元素.