代码如下:
unordered_map<int,int> un;
for(auto it=un.begin();it!=un.end();++it)
{
int th =it->first+k;
auto itf=un.find(th);
if(itf != un.end())
//if(un[it->first+k] == 1) //Can use it, it will insert default value, map should use find!
{
if(k ==0)
{
if( itf->second >1)
count++;
}
else
count++;
}
}其中un[it->first+k]的用法是错误的,因为取下标运算符会在不存在此元素的前提下,插入<int,default value>的元素,改变了un的大小,导致map遍历的提前结束。
附带一下stl中map的实现:
mapped_type& operator[](const key_type& _Keyval)
{ // find element matching _Keyval or insert with default mapped
iterator _Where = this->lower_bound(_Keyval);
if (_Where == this->end()
|| this->comp(_Keyval, this->_Key(_Where._Mynode())))
_Where = this->insert(_Where,
value_type(_Keyval, mapped_type()));
return ((*_Where).second);
} 可见明显的insert语句,所以map的查找,还是老老实实的用find比较合适。
本文详细解析了C++ STL中的map数据结构,并重点强调了在遍历过程中使用find方法而非[]运算符的原因。通过具体示例展示了[]运算符在未找到元素时会自动插入默认值的行为,可能导致遍历提前结束的问题。
931

被折叠的 条评论
为什么被折叠?



