# C++ map: 新增数据的 3 种常用方法及区别

> C++中，在 map 中插入数据，有 3 种方法：operator[]，insert()，emplace()。时间复杂度都是 O(log(n)) 。 使用 operator[] 时，value 类型需要默认的构造函数。

- Source: https://acytoo.com/ladder/c++-map-different-insert-functions/
- Author: acytoo
- Published: 2021-04-15
- Updated: 2021-04-16
- Language: zh-CN
- Section: ladder
- Tags: c++

C++中，在 ```map``` 中插入数据，有 3 种方法：```operator[]```，```insert()```，```emplace()```。时间复杂度都是 $\mathcal{O}(\log(n))$ 。

```operator[]``` 与 ```insert()``` 的区别主要是，在 ```map``` 中已有 ```key``` 时，```insert()``` 不会修改 ```map```，而 ```operator[]``` 会更新 ```map``` 中 ```key``` 对应的 ```value```。

```insert()``` 与 ```emplace()``` 的主要区别是，```insert()``` 先在某个位置新建一个 ```value_type``` （在 ```map``` 中，这是一个```pair```），然后根据 ```key``` 是否重复，来判断是否插入到 ```map```，而 ```emplace()``` 是直接在 ```map``` 中新建一个 ```pair``` ，然后根据 ```key``` 是否重复，来判断是否从 ```map``` 中销毁。

通常情况下，```emplace()``` 比 ```insert()``` 快，因为减少了对象的创建与移动。

--------------------------------------

```cpp
MyClass value1 = ...;
map<int, MyClass> m;
m[1] = value1;
```
使用 ```operator[]``` 时，value 类型需要默认的构造函数。```m[1] = value1;``` 这行代码在执行时，会先使用默认值构造 ```m[1]```，然后对 key 赋值。

&nbsp;

参考：

[GeeksforGeeks: Inserting elements in std::map (insert, emplace and operator \[\])](https://www.geeksforgeeks.org/inserting-elements-in-stdmap-insert-emplace-and-operator/)

[stackoverflow: What is the preferred/idiomatic way to insert into a map?](https://stackoverflow.com/questions/4286670/what-is-the-preferred-idiomatic-way-to-insert-into-a-map)

[stackoverflow: In STL maps, is it better to use map::insert than \[\]?](https://stackoverflow.com/questions/326062/in-stl-maps-is-it-better-to-use-mapinsert-than)
