Iterator access performance for STL map vs. vector?

前端 未结 6 1471
星月不相逢
星月不相逢 2021-02-05 17:15

What is the performance difference between using an iterator to loop through an STL map, versus a vector? I\'d like to use the map key for insertion, deletion, and some accesses

6条回答
  •  太阳男子
    2021-02-05 17:47

    With both map and vector, iterating through the entire collection is O(N). however (like list vs vector) vector stores elements contiguously, so accessing the next element is much cheaper because it will use cache optimally, whereas the map won't.

    But since you need to have lookup based on keys, there isn't really an alternative. You could use a vector of pairs sorted on the first element, but if the collection needs to be mutable this is going to be very slow. Just use a map.

提交回复
热议问题