STL map insertion efficiency: [] vs. insert

前端 未结 6 1695
走了就别回头了
走了就别回头了 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 22:44

    My take on it: Worth reminding that maps is a balanced binary tree, most of the modifications and checks take O(logN).

    Depends really on the problem you are trying to solve.

    1) if you just want to insert the value knowing that it is not there yet, then [] would do two things: a) check if the item is there or not b) if it is not there will create pair and do what insert does ( double work of O( logN ) ), so I would use insert.

    2) if you are not sure if it is there or not, then a) if you did check if the item is there by doing something like if( map.find( item ) == mp.end() ) couple of lines above somewhere, then use insert, because of double work [] would perform b) if you didn't check, then it depends, cause insert won't modify the value if it is there, [] will, otherwise they are equal

提交回复
热议问题