c++中stl的map的[]取下标运算符需要慎用

来源:互联网 发布:文学创作知乎 编辑:程序博客网 时间:2024/06/06 04:20

代码如下:

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比较合适。