首页 > 其他 > 详细

stl::map

时间:2014-11-21 12:30:37      阅读:132      评论:0      收藏:0      [点我收藏+]

stl::map是个很危险的容器,因为当用[]访问map元素时不是只读,还伴随着写操作:当访问的key值不存在时会自动插入。

以下引自:http://www.cplusplus.com/reference/map/map/operator[]/

If k matches the key of an element in the container, the function returns a reference to its mapped value.

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

A similar member function, map::at, has the same behavior when an element with the key exists, but throws an exception when it does not.

A call to this function is equivalent to:
(*((this->insert(make_pair(k,mapped_type()))).first)).second

所以除非明确知道肯定不会出现访问到不存在key值的情况,否则一定不要用[]来访问,要用map::find。参考:http://www.cplusplus.com/reference/map/map/find/

 

stl::map

原文:http://www.cnblogs.com/wantnon/p/4112479.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!