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() 快,因为减少了对象的创建与移动。
MyClass value1 = ...;
map<int, MyClass> m;
m[1] = value1;
使用 operator[] 时,value 类型需要默认的构造函数。m[1] = value1; 这行代码在执行时,会先使用默认值构造 m[1],然后对 key 赋值。
参考:
GeeksforGeeks: Inserting elements in std::map (insert, emplace and operator [])
stackoverflow: What is the preferred/idiomatic way to insert into a map?
stackoverflow: In STL maps, is it better to use map::insert than []?