【问题标题】:why does std::set<>::find return a const? [duplicate]为什么 std::set<>::find 返回一个常量? [复制]
【发布时间】:2012-02-26 17:01:59
【问题描述】:

可能重复:
C++ STL set update is tedious: I can't change an element in place

我想使用std::set&lt;&gt; 来计算某个值的出现次数并同时对对象进行排序。为此我创建了一个类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-&gt;inc() 时抱怨:

error: passing 'const RadiusCounter' as 'this' argument of 'void RadiusCounter::inc()' discards qualifiers

为什么*itr 中的实例在这里是一个常量?

【问题讨论】:

    标签: c++ stl set constants


    【解决方案1】:

    因为您不能修改 std::set 中的元素。如果可以的话,它可能会破坏严格-弱排序不变量,从而导致未定义的行为。

    如果你想修改一个元素,那么你应该删除这个元素,然后插入一个新元素。

    【讨论】:

      【解决方案2】:

      另外,看来你想要的只是

      typedef int Radius;
      typedef int Counter
      std::map<Radius, Conunter>theRadii;
      
      ...
      
      theRadii[getSomeValue()]++;
      

      【讨论】:

        【解决方案3】:

        碰巧几个小时前我已经回答了这个问题:https://stackoverflow.com/a/9452445/766580。基本上,您无法更改set 元素的值,因为set 无法知道您更改了什么。如果您想这样做,您需要删除并重新插入修改后的值。

        【讨论】:

        • 如果您发现类似问题,请将问题标记为重复。就目前而言,您的答案并不是真正的答案,它只是指向其他地方的链接。
        猜你喜欢
        • 1970-01-01
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 2017-09-23
        • 2011-05-22
        • 2020-07-04
        • 2012-05-04
        相关资源
        最近更新 更多