关联容器(第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中文版》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值