STL Containers - difference between vector, list and deque

后端 未结 2 1757
你的背包
你的背包 2021-02-01 08:10

Should I use deque instead of vector if i\'d like to push elements also in the beginning of the container? When should I use list and what\'s the point of it?

2条回答
  •  生来不讨喜
    2021-02-01 08:34

    Use deque if you need efficient insertion/removal at the beginning and end of the sequence and random access; use list if you need efficient insertion anywhere, at the sacrifice of random access. Iterators and references to list elements are very stable under almost any mutation of the container, while deque has very peculiar iterator and reference invalidation rules (so check them out carefully).

    Also, list is a node-based container, while a deque uses chunks of contiguous memory, so memory locality may have performance effects that cannot be captured by asymptotic complexity estimates.

    deque can serve as a replacement for vector almost everywhere and should probably have been considered the "default" container in C++ (on account of its more flexible memory requirements); the only reason to prefer vector is when you must have a guaranteed contiguous memory layout of your sequence.

提交回复
热议问题