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

代码如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值