2012-02-26 21 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

関連する問題