首页 > 技术文章 > stl::map

wantnon 2014-11-21 11:41 原文

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/

 

推荐阅读