C++ map下标操作[]和insert区别

在构建map时候,我们是使用insert和[]有什么区别呢?
哪个更好呢?
哪个效率更高呢?
哪个更安全呢?

首先需要明确的是:
map中不允许存在相同的key

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

直接分析代码:

#include <iostream>
#include <map>
#include <utility>
using namespace std;

class Sample
{
  static int _noOfObjects;
  int _objectNo;
  
public:
  Sample() :
  
  _objectNo(_noOfObjects++)
  {
    std::cout << "Inside default constructor of object " << _objectNo << std::endl;
  }

  Sample(const Sample& sample) :
    _objectNo(_noOfObjects++)
  {
    std::cout << "Inside copy constructor of object " << _objectNo << std::endl;
  }

  ~Sample()
  {
    std::cout << "Destroying object " << _objectNo << std::endl;
  }
};

int Sample::_noOfObjects = 0;


int main(int argc, char* argv[])
{
  Sample sample;
  std::map<int, Sample> map;
  
  //map.insert(std::make_pair(1, sample));
  map[1] = sample;
  return 0;
}
使用[]的输出:

Inside default constructor of object 0
Inside default constructor of object 1
Destroying object 0
Destroying object 0

使用insert输出

Inside default constructor of object 0
Inside copy constructor of object 1
Inside copy constructor of object 2
Destroying object 1
Destroying object 2
Destroying object 0

区别

insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.

operator[] needs the default constructor because the map checks if the element exists. If it doesn’t then it creates one using default constructor and returns a reference (or const reference to it).

insert is better from the point of exception safety.

map[key] = value 是两步走:
map[key] - 创建一个map元素,并使用default value.
= value - 将value 赋值到刚刚创建的map元素

An exception may happen at the second step. As result the operation will be only partially done (a new element was added into map, but that element was not initialized with value). The situation when an operation is not complete, but the system state is modified, is called the operation with “side effect”.

这里有更通俗的对比:
如果一个key存在, operator[] 对这个key-value进行重写
如果一个key存在, insert 不会对原来的key-value进行重写

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值