我注意到在有效的STL

向量是这样一种序列 默认情况下应该使用。

这是什么意思?似乎忽略效率向量可以做任何事情。

谁能给我一个场景,其中向量不是一个可行的选择,但必须使用列表?


当前回答

必须使用list的唯一硬性规则是需要将指针分发到容器元素的地方。

与vector不同,你知道元素的内存不会被重新分配。如果可以,那么可能会有指向未使用内存的指针,这在最好的情况下是一个大禁忌,在最坏的情况下是SEGFAULT。

(从技术上讲,*_ptr的向量也可以工作,但在这种情况下,你是在模拟列表,所以这只是语义。)

其他软规则与将元素插入容器中间可能存在的性能问题有关,因此最好使用list。

其他回答

在向量和列表的情况下,对我来说,主要的区别如下:

向量

A vector stores its elements in contiguous memory. Therefore, random access is possible inside a vector which means that accessing an element of a vector is very fast because we can simply multiply the base address with the item index to access that element. In fact, it takes only O(1) or constant time for this purpose. Since a vector basically wraps an array, every time you insert an element into the vector (dynamic array), it has to resize itself by finding a new contiguous block of memory to accommodate the new elements which is time-costly. It does not consume extra memory to store any pointers to other elements within it.

list

A list stores its elements in non-contiguous memory. Therefore, random access is not possible inside a list which means that to access its elements we have to use the pointers and traverse the list which is slower relative to vector. This takes O(n) or linear time which is slower than O(1). Since a list uses non-contiguous memory, the time taken to insert an element inside a list is a lot more efficient than in the case of its vector counterpart because reallocation of memory is avoided. It consumes extra memory to store pointers to the element before and after a particular element.

因此,记住这些区别,我们通常会考虑内存、频繁的随机访问和插入来决定给定场景中向量和列表的胜者。

如果你不需要经常插入元素,那么向量会更有效。它具有比列表更好的CPU缓存位置。换句话说,访问一个元素使得下一个元素很有可能存在于缓存中,并且可以在不读取慢速RAM的情况下被检索。

想要重复将大量项插入序列末尾以外的任何位置的情况。

看看每种不同类型的容器的复杂度保证:

标准容器的复杂性保证是什么?

必须使用list的唯一硬性规则是需要将指针分发到容器元素的地方。

与vector不同,你知道元素的内存不会被重新分配。如果可以,那么可能会有指向未使用内存的指针,这在最好的情况下是一个大禁忌,在最坏的情况下是SEGFAULT。

(从技术上讲,*_ptr的向量也可以工作,但在这种情况下,你是在模拟列表,所以这只是语义。)

其他软规则与将元素插入容器中间可能存在的性能问题有关,因此最好使用list。

我班上的学生似乎无法向我解释什么时候使用向量更有效,但他们在建议我使用列表时看起来很高兴。

这是我的理解

列表: 每一项都包含下一个或上一个元素的地址,所以有了这个功能,你可以随机项,即使它们没有排序,顺序也不会改变:如果你的内存是碎片化的,它是有效的。 但是它还有一个非常大的优势:你可以很容易地插入/删除项,因为你唯一需要做的就是改变一些指针。 缺点: 要读一个随机的条目,你必须从一个条目跳到另一个条目,直到你找到正确的地址。

Vectors: When using vectors, the memory is much more organized like regular arrays: each n-th items is stored just after (n-1)th item and before (n+1)th item. Why is it better than list ? Because it allow fast random access. Here is how: if you know the size of an item in a vector, and if they are contiguous in memory, you can easily predict where the n-th item is; you don't have to browse all the item of a list to read the one you want, with vector, you directly read it, with a list you can't. On the other hand, modify the vector array or change a value is much more slow.

列表更适合用于跟踪可以在内存中添加/删除的对象。 当您希望从大量单个项中访问一个元素时,向量更适合。

我不知道列表是如何优化的,但你必须知道,如果你想要快速读取访问,你应该使用向量,因为STL固定列表有多好,它在读取访问方面不会像向量那样快。