C++ 为什么std::设置<>;::找到一个常数?
可能重复:C++ 为什么std::设置<>;::找到一个常数?,c++,stl,set,constants,C++,Stl,Set,Constants,可能重复: 我想使用std::set来计算某个值出现的次数,同时对对象进行排序。为此,我创建了一个类radiusconter class RadiusCounter { public: RadiusCounter(const ullong& ir) : r(ir) { counter = 1ULL; } void inc() { ++counter; } ullong get() const { return counter;} ullong getR(
我想使用
std::set
来计算某个值出现的次数,同时对对象进行排序。为此,我创建了一个类radiusconter
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();}
为什么
*itr
中的实例在这里是常量?因为您不能修改std::set
中的元素。如果可以,它可能会破坏严格的弱序不变量,导致未定义的行为
如果要修改某个元素,则应删除该元素,然后插入一个新元素。碰巧我几个小时前已经回答了这个问题:。基本上,您不能更改
set
元素的值,因为set
无法知道您更改了什么。如果要执行此操作,您需要删除并重新插入修改后的值。作为补充,您似乎只需要
typedef int Radius;
typedef int Counter
std::map<Radius, Conunter>theRadii;
...
theRadii[getSomeValue()]++;
typedef int半径;
类型定义整数计数器
标准::maptheRadii;
...
theRadii[getSomeValue()]++;
如果您发现类似问题,请将该问题标记为重复问题。就目前而言,你的答案并不是真正的答案,它只是指向其他地方的链接。
error: passing 'const RadiusCounter' as 'this' argument of 'void RadiusCounter::inc()' discards qualifiers
typedef int Radius;
typedef int Counter
std::map<Radius, Conunter>theRadii;
...
theRadii[getSomeValue()]++;