vector or map, which one to use?

前端 未结 7 1422
渐次进展
渐次进展 2020-11-28 03:00

I\'ve heard many people say that if the number of expected elements in the container is relatively small, it is better to use std::vector instead of std::

7条回答
  •  隐瞒了意图╮
    2020-11-28 03:39

    Maps are usually implemented as binary search trees, and walking a binary tree always comes with a little overhead (performing comparisons, walking links, etc.) Vectors are basically just arrays. For very small amounts of data, maybe 8 or 12 elements, sometimes it's faster just to do a linear search over an array than to walk a binary search tree.

    You can run some timings yourself to see where the break-even point is -- time a search over four elements, then eight, then sixteen, and so on to find the sweet spot for your particular implementation of the STL.

    Maps do tend to have a bunch of small allocations all over the heap, whereas vectors are contiguous so the cache-hit rate of vectors can sometimes be a little better in cases where you're iterating over all the elements from front to back.

提交回复
热议问题