在构建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进行重写