我注意到在有效的STL

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

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

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


当前回答

〇简单一点 在一天结束的时候,当你在c++中选择容器时感到困惑时,使用下面的流程图图像(对我说谢谢):-

向量,

Vector基于传染性记忆 矢量是小数据集的一种方式 Vector在遍历数据集时执行最快 向量插入删除在巨大数据集上很慢,但在非常数据集上很快 小

列表,

List基于堆内存 列表是非常庞大的数据集 List在遍历小数据集时相对较慢,但在 巨大的气候资料 列表插入删除在大数据集上速度快,但在小数据集上速度慢 的

其他回答

这里的大多数答案都遗漏了一个重要的细节:为什么?

你想在集装箱里放些什么?

如果它是int型的集合,那么std::list在任何情况下都将丢失,不管你是否可以重新分配,你只从前面删除,等等。遍历列表的速度较慢,每次插入都需要与分配器进行交互。要准备一个例子是极其困难的,其中list<int>击败vector<int>。即使这样,deque<int>可能更好或关闭,而不仅仅是使用列表,这将有更大的内存开销。

然而,如果您正在处理大而丑陋的数据块——而且数量很少——您不想在插入时过度分配,而由于重新分配而进行复制将是一场灾难——那么您可能,也许,使用list<UglyBlob>比使用vector<UglyBlob>更好。

不过,如果你切换到vector<UglyBlob*>或甚至vector<shared_ptr<UglyBlob> >, - list仍然会滞后。

因此,访问模式、目标元素数量等仍然会影响比较,但在我看来,元素大小、复制成本等。

当你在序列中间有很多插入或删除时。例如,内存管理器。

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

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

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

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

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

向量

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.

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