关联容器(第3章)(条款24,25)

条款24:当效率至关重要时,请在 map::operator[] 与 map::insert 之间谨慎做出选择

看如下operator[]的官方文档说明:

std::map::operator[]

  • C++98
  • C++11
  •  
mapped_type& operator[] (const key_type& k);
mapped_type& operator[] (key_type&& k);

Access element

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

也就是如果容器中没有元素,则会插入一个,value用默认构造函数构造,然后返回引用!!!显然,如果你是要直接插入新元素,用operator[]会多发生一次默认构造

因此,条款建议如果要更新一个已有的映射表元素,则应该优先选择operator[],但是如果要添加一个新的元素,那么最好还是选择insert。

条款25:熟悉非标准的散列容器

特别说明,C++11以后标准库中已经新增了 散列容器 unordered|_set/multiset, unordered_map/multimap,所以这个条款的讨论已经过时了,我这儿列一个自定义类使用散列容器的代码

https://mp.csdn.net/editor/html/111870855

参考:《Effective STL中文版》

猜你喜欢

转载自blog.csdn.net/u010323563/article/details/112452544
今日推荐