假设有以下变量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;
});