自从VS2010开始,set的iterator类型自动就是const的引用类型,因此当set保存的是类类型时,对iterator解引用无法调用类的非const成员。
解决方法为:
//item是一个类,bool isEnd()是Item的一个成员
for (set<Item>::iterator i = ItemSet.begin(); i != ItemSet.end(); i++)
{
const Item &item1 = const_cast<Item&>(*i);
Item &item2 = const_cast<Item&>(item1);
if (item2.isEnd())
{//do something}
const_cast:(转自百度百科)
用法:const_cast<type_id> (expression)
该运算符用来修改类型的const或volatile属性。除了const 或volatile修饰之外, type_id和expression的类型是一样的。
一、常量指针被转化成非常量的指针,并且仍然指向原来的对象;
二、常量引用被转换成非常量的引用,并且仍然指向原来的对象;
The iterator should give you a const reference (and that's what the Standard says it should do), because changing the thing referred to would destroy the validity of the set's underlying data structure - the set doesn't "know" that the field you are changing is not actually part of the key. The alternatives are to make changes by removing and re-adding, or to use a std::map instead.
因为改变引用指向的对象会破坏set隐藏的数据结构的正确性。