Set 的iterator(迭代器)自动为const的引用类型

自从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的类型是一样的。
一、常量指针被转化成非常量的指针,并且仍然指向原来的对象;
二、常量引用被转换成非常量的引用,并且仍然指向原来的对象;


为什么要设置为const reference?

转自:http://stackoverflow.com/questions/2523139/const-references-when-dereferencing-iterator-on-set-starting-from-visual-studio

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隐藏的数据结构的正确性。




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值