一直走寻常路,平平淡淡
偶遇新人“热血”,涟漪泛泛
对于list、vector、map等的使用,一直都是凭感觉在用,没有深入其中看个究竟
这也就容易导致知其然而不知其所以然
也难以将已有功能应用到极致
这种毛病应该改改
今天就遇到一个相关问题,帮调试一段代码,安装一贯思维百思不得其解,代码如下:
std::map<int, int> testmap;
int value = testmap[0];
想着,这么写应该会挂,而运行结果却很正常,只是凭空增加了一条记录。
事实摆在眼前,没有理由反驳,看一下源码就一目了然了:
mapped_type& operator[](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,
_STD pair<key_type, mapped_type>(
_STD move(_Keyval),
mapped_type()));
return ((*_Where).second);
}
以后要注意了,还是先find吧