2012-02-26 113 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 2012-02-26 17:19:06

8

因爲您無法修改std::set中的元素。如果可以的話,它將允許它打破嚴格 - 弱的排序不變性的可能性,導致未定義的行爲。

如果你想修改一個元素,那麼你應該擦除元素,並插入一個新元素。

1

碰巧我幾個小時前已經回答了這個問題:https://stackoverflow.com/a/9452445/766580。基本上,您無法更改set元素的值,因爲set無法知道您更改了什麼。如果你想這樣做,你需要刪除並重新插入修改後的值。

+0

請標誌的問題爲重複的,如果你發現這樣的事情。就目前而言,你的回答並不是一個真正的答案,它只是一個連接其他地方的鏈接。 – Mat 2012-02-26 17:07:04

相關問題