可能重复:
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中的实例在这里?
| 归档时间: |
|
| 查看次数: |
3087 次 |
| 最近记录: |