📜  向量和列表的区别

📅  最后修改于: 2021-09-13 02:07:53             🧑  作者: Mango

Vector: Vector 是一种动态数组,可以在插入或删除元素后自动调整大小。 vector 中的元素被放置在连续的存储中,以便可以使用迭代器访问和遍历它们。元素插入到向量的末尾。
例子:

vector v;
v.insert(5);
v.delete();

List: List是一个双链序列,支持向前和向后遍历。在开始、结束和中间插入和删除所花费的时间是恒定的。它具有非连续内存,并且没有预先分配的内存。
例子:

list  l;
l.insert_begin(5);
l.delete_end();

向量与列表

下表列出了 Vector 和 List 之间的差异:

Vector List
It has contiguous memory. While it has non-contiguous memory.
It is synchronized. While it is not synchronized.
Vector may have a default size. List does not have default size.
In vector, each element only requires the space for itself only. In list, each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.
Insertion at the end requires constant time but insertion elsewhere is costly. Insertion is cheap no matter where in the list it occurs.
Vector is thread safe. List is not thread safe.
Deletion at the end of the vector needs constant time but for the rest it is O(n). Deletion is cheap no matter where in the list it occurs.
Random access of elements is possible. Random access of elements is not possible.
Iterators become invalid if elements are added to or removed from the vector. Iterators are valid if elements are added to or removed from the list.