map中[]运算符和find的区别

map的下标运算符[]的作用是:将关键码作为下标去执行查找,并返回对应的值;如果不存在这个关键码,就将一个具有该关键码和值类型的默认值的项插入这个map。

map<string,string> m;
m["first"] = "hello";
m["second"] = "world";

cout<<"[]查找之前"<<endl;
map<string,string>::iterator it = m.begin();
for(;it!=m.end();++it)
{
    cout<<it->first<<" "<<it->second<<endl;
}
cout<<endl;
cout<<"查找之后"<<endl;
if(m["third"] == "test")
{
    m["third"] == "testresult";
}
it = m.begin();
for(;it!=m.end();++it)
{
        cout<<it->first<<" "<<it->second<<endl;
}

这里写图片描述

//operator []的源码
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);
}

map的find函数:用关键码执行查找,找到了返回该位置的迭代器;如果不存在这个关键码,就返回尾迭代器。

map<string,string> f;
f.insert(make_pair("first","hello"));
f.insert(make_pair("second","world"));
cout<<"find查找之前"<<endl;
map<string,string>::iterator it = f.find("third");
if(it != f.end())
{
    cout<<it->second<<endl;
}
else
{
    cout<<"没找到"<<endl;
}
cout<<endl;
cout<<"find查找之后"<<endl;
it = f.begin();
for(;it!=f.end();++it)
{
    cout<<it->first<<" "<<it->second<<endl;
}

这里写图片描述

//再看看find的源码
const_iterator find(const key_type& _Keyval) const
{ // find an element in nonmutable sequence that matches _Keyval
const_iterator _Where = lower_bound(_Keyval);
return (_Where == end()
|| _DEBUG_LT_PRED(this->comp,
_Keyval, _Key(_Where._Mynode()))
? end() : _Where);
}
  • 10
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值