가능한 중복 :
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