2012-02-26 2 views
0

가능한 중복 :
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 인 이유는 무엇입니까?

답변

3

는 또한, 당신이 뭔가를 발견하면 그냥

typedef int Radius; 
typedef int Counter 
std::map<Radius, Conunter>theRadii; 

... 

theRadii[getSomeValue()]++; 
+0

네, 맞습니다, 고마워요! – Thomas

8

std::set의 요소를 수정할 수 없기 때문에 가능한 경우 엄격한 약한 순서 불변성을 깨뜨려 정의되지 않은 동작을 초래할 가능성을 허용합니다.

요소를 수정하려면 요소를 지우고 새 요소를 삽입해야합니다.

1

나는 벌써 몇 시간 전에이 질문에 대답했습니다 : https://stackoverflow.com/a/9452445/766580. 기본적으로 set은 변경 한 내용을 알 수 없기 때문에 set 요소의 값을 변경할 수 없습니다. 이렇게하려면 수정 된 값을 제거했다가 다시 삽입해야합니다.

+0

하시기 바랍니다 플래그 중복으로 질문을 원하는 것 같다. 그것이 그대로, 당신의 대답은 정말로 대답이 아니며 단지 다른 곳으로의 링크 일뿐입니다. – Mat

관련 문제