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.

 

转载于:https://www.cnblogs.com/touchdown/p/5142490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值