【发布时间】:2012-02-26 17:01:59
【问题描述】:
可能重复:
C++ STL set update is tedious: I can't change an element in place
我想使用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;
};
(析构函数什么都不做)连同比较运算符:
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();}
现在我想这样使用它:
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();
但现在编译器在调用itr->inc() 时抱怨:
error: passing 'const RadiusCounter' as 'this' argument of 'void RadiusCounter::inc()' discards qualifiers
为什么*itr 中的实例在这里是一个常量?
【问题讨论】: