STL map insertion efficiency: [] vs. insert

前端 未结 6 1704
走了就别回头了
走了就别回头了 2021-02-12 22:23

There are two ways of map insertion:

m[key] = val;

Or

m.insert(make_pair(key, val));

My question is, which op

6条回答
  •  故里飘歌
    2021-02-12 23:00

    Performance wise I think they are mostly the same in general. There may be some exceptions for a map with large objects, in which case you should use [] or perhaps emplace which creates fewer temporary objects than 'insert'. See the discussion here for details.

    You can, however, get a performance bump in special cases if you use the 'hint' function on the insert operator. So, looking at option 2 from here:

    iterator insert (const_iterator position, const value_type& val);
    

    the 'insert' operation can be reduced to constant time (from log(n)) if you give a good hint (often the case if you know you are adding things at the back of your map).

提交回复
热议问题