vector VS list in C++

本文深入探讨了Java中Vector与List的区别,重点分析了它们在内存使用、访问速度、插入删除操作以及缓存优化等方面的差异。Vector提供连续内存、预分配空间和快速随机访问,但迭代器在元素插入后失效;而List不提供连续内存,无预分配,插入删除灵活,但随机访问可能较慢。文章最后比较了两者在不同场景下的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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、付费专栏及课程。

余额充值