std::map的一次错误应用(日积月累)

1 篇文章 0 订阅
1 篇文章 0 订阅

假设有以下变量std::map<int, int>::iterator it;  

问:*it返回的是什么类型?

答:以前一直以为是std::pair<int,int> &,而且以前将其做为只读变量使用也没出过错。直到最近,才发现自己原来错了,错误代码见下面:

//std::map<int, int> mapInt;

//此处省略变量的初始化过程

std::for_each(mapInt.begin(), mapInt.end(),  [](const std::pair<int,int> &pair)

{

         std::pair<int,int> &v =const_cast<std::pair<int,int>&>(pair);

         v.second = v.first * v.first;

});

结果执行完以上代码后发现mapInt里面的值没有任何变化。为此着实苦恼了一番,直到去阅读std::map源代码才发现,原来*it 返回的应该是std::pair<constint,int> &。 由于做std::for_each时,pair类型与*it的返回值不匹配,从而使得编译器通过拷贝构造生成了一个临时的std::pair<int,int>类型,但这样一来不仅效率变低了,接下来的修改动作自然也就失败了。

而修改成如下这样就OK了:

//std::map<int, int> mapInt;

//此处省略变量的初始化过程

std::for_each(mapInt.begin(),mapInt.end(), [](std::map< int,int >::reference pair)

{

         pair.second = pair.first * pair.first;

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值