2

对于我的应用程序,我使用的是 STD 向量。我在最后插入向量,但是从向量中随机擦除,即元素可以从中间,前面的任何地方擦除。这两个只是要求,1)在末尾插入 2)从任何地方擦除。

所以我应该使用 STD 列表,因为擦除确实会移动数据。或者我会出于任何原因在我的代码中保留 Vector ?

请发表评论,如果 Vector 是更好的选择,这里的 List 会更好吗?

4

5 回答 5

4

One key reason to use std::vector over std::list is cache locality. A list is terrible in this regard, because its elements can be (and usually are) fragmented in your memory. This will degrade performance significantly.

Some would recommend using std::vector almost always. In terms of performance, cache locality is often more important than the complexity of insertion or deletion.

Here's a video about Bjarne Stroustrup's opinion regarding subject.

于 2013-11-05T14:30:37.737 回答
2

我会向您推荐这份备忘单,结论就是清单。

在此处输入图像描述

于 2013-11-05T14:08:26.867 回答
1

List is better in this case most probably. The advantage of a list over vector is that it supports deletion at arbitrary position with constant complexity. A vector would only be better choice if you require constant index operation of elements of the container. Still you have to take into consideration how is the element you would like to delete passed to your function for deletion. If you only pass an index, vector will be able to find the element in constant time, while in list you will have to iterate. In this case I would benchmark the two solution, but still I would bet on list performing better.

于 2013-11-05T14:09:22.087 回答
1

列表支持在恒定时间内在任意但已知的位置删除。

找到那个位置需要线性时间,就像修改一个向量一样。

该列表的唯一优点是如果您在(大约)相同的位置重复擦除(或插入)。

如果您或多或少地随机擦除,则向量的更好的内存局部性最终可能会胜出。

唯一确定的方法是测量和比较。

于 2013-11-05T14:16:15.290 回答
0

这取决于许多因素以及您如何使用数据。

一个因素:您是否需要一个保持集合顺序的擦除?或者你可以忍受不断变化的订单?

其他因素:集合中有哪些数据?(数字:整数/浮点数)|| 指针 || 对象

不守秩序

如果数据是基本数字或指针,您可以继续使用vector,要删除一个元素,您可以将向量的最后一个元素复制到已删除的位置,然后pop_back(). 这样可以避免移动所有数据。

如果使用对象,如果您需要复制的对象很小,您仍然可以使用相同的方法。

维持秩序

也许 List 会是你的朋友,不过,还是会建议进行一些测试,这取决于数据的大小、列表的大小等

于 2013-11-05T14:24:50.403 回答