vector VS list in C++

 

vector is like ArrayList in Java.

vector:

  • Continuous memory.
  • Underlying array implementation.
  • Pre-allocate space for future element. This means extra space rather than necessary
  • Random access is fast, since looking up is index based.
  • No extra space for element. Just the element type itself.
  • Iterator is invalid after element insertions and erasures.
  • Insert element at the end is amortised constant time, while elsewhere is O(n).
  • Can re-allocate memory for the entire vector any time when you add an element.
  • Remove element at the end is constant time, while elsewhere is O(n).
  • Element erasure does not free memory

list:

  • Not continuous memory.
  • No pre-allocate space for future elements.
  • There are extra storage needed for node which holds the element, including pointers to the next and previous elements.
  • Insertion and deletion are cheap no matter where element is(No guarantee that list is faster. Needs to based on real application).
  • Access element can be expensive.
  • Iterator is still valid after insertion and deletion.

 

vector is a WIN over list in:

  • Random access
  • If you don't insert elements often, since vector has much better CPU cache locality than list, which means that accessing one element will make the next element very likely in the cache and can be retrieved without reading from slow RAM.

 

list is WIN over vector in:

  • Guaranteed constant time for inserting element at the end, since vector can lead to memory allocation and copying of original elements. However, vector can get amortised constant time.
  • Doing many insertions or erasures of elements in positions other than the end.

 

posted on 2016-01-19 16:04  touchdown  阅读(167)  评论(0编辑  收藏  举报

导航