STL map insertion efficiency: [] vs. insert

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

    Both accomplish different things.

    m[key] = val;
    

    Will insert a new key-value pair if the key doesn't exist already, or it will overwrite the old value mapped to the key if it already exists.

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

    Will only insert the pair if key doesn't exist yet, it will never overwrite the old value. So, choose accordingly to what you want to accomplish.
    For the question what is more efficient: profile. :P Probably the first way I'd say though. The assignment (aka copy) is the case for both ways, so the only difference lies in construction. As we all know and should implement, a default construction should basically be a no-op, and thus be very efficient. A copy is exactly that - a copy. So in way one we get a "no-op" and a copy, and in way two we get two copies.
    Edit: In the end, trust what your profiling tells you. My analysis was off like @Matthieu mentions in his comment, but that was my guessing. :)


    Then, we have C++0x coming, and the double-copy on the second way will be naught, as the pair can simply be moved now. So in the end, I think it falls back on my first point: Use the right way to accomplish the thing you want to do.

提交回复
热议问题