C++中Vector和List 的不同

转自:https://thispointer.com/difference-between-vector-and-list-in-c/

Both vector and list are sequential containers of C++ Standard Template Library. But there are many differences between them because of their internal implementation i.e.

List stores elements at non contiguous memory location i.e. it internally uses a doubly linked list i.e.

linkedlist

Whereas, vector stores elements at contiguous memory locations like an array i.e.

 

array

 

std::vector vs std::list

1.) Insertion and Deletion

Insertion and Deletion in List is very efficient as compared to vector because to insert an element in list at start, end or middle, internally just a couple of pointers are swapped.

Whereas, in vector insertion and deletion at start or middle will make all elements to shift by one. Also, if there is insufficient contiguous memory in vector at the time of insertion, then a new contiguous memory will be allocated and all elements will be copied there.

So, insertion and deletion in list is much efficient than vector in c++.

2.) Random Access:

As List is internally implemented as doubly linked list, therefore no random access is possible in List. It means, to access 15th element in list we need to iterate through first 14 elements in list one by one.

Whereas, vector stores elements at contiguous memory locations like an array. Therefore, in vector random access is possible i.e. we can directly access the 15th element in vector using operator [] i.e.

std::vector<int> vec(20);

vec[15] = 10;


So, we can not use std::list with some of the STL algorithm that needs the random access operators like std::sort.

 

3.) Iterator Invalidation

Deleting or Inserting an element in List does not invalidate any iterator because during insertion and deletion no element is moved from its position only a couple pointers are changed.

 

Whereas, in vector insertion and deletion can invalidate the iterators. For more details about vector Iterator Invalidation, check this article i.e.

std::vector and Iterator Invalidation

4.) Special Member functions

As std::list do not provide random access, there many STL algorithms that uses Random Access Iterators can not be used with List. Hence std::list provides some extra functions for Sorting, Splicing, Removing elements and identifying unique elements.

Vector provides the random access and hence can be used with STL algorithms that uses Random Access Iterators.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值