此文章转载自:https://blog.csdn.net/weixin_39831546/article/details/78314476
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);
}