可能重複:
C++ STL set update is tedious: I can't change an element in place爲什麼std :: set <> :: find返回一個const?
我想用一個std::set<>
算有一定的價值數出現次數和simultaneosly的對象進行排序。爲此,我創建了一個類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
中的實例是const?
是的,你是對的,謝謝! – Thomas 2012-02-26 17:19:06