我注意到在有效的STL
向量是这样一种序列 默认情况下应该使用。
这是什么意思?似乎忽略效率向量可以做任何事情。
谁能给我一个场景,其中向量不是一个可行的选择,但必须使用列表?
我注意到在有效的STL
向量是这样一种序列 默认情况下应该使用。
这是什么意思?似乎忽略效率向量可以做任何事情。
谁能给我一个场景,其中向量不是一个可行的选择,但必须使用列表?
当前回答
当你想在容器之间移动对象时,你可以使用list::splice。
例如,一个图划分算法可以将常数数量的对象递归地划分到数量不断增加的容器中。对象应该初始化一次,并始终保持在内存中的相同位置。通过重新链接来重新排列比重新分配要快得多。
Edit: as libraries prepare to implement C++0x, the general case of splicing a subsequence into a list is becoming linear complexity with the length of the sequence. This is because splice (now) needs to iterate over the sequence to count the number of elements in it. (Because the list needs to record its size.) Simply counting and re-linking the list is still faster than any alternative, and splicing an entire list or a single element are special cases with constant complexity. But, if you have long sequences to splice, you might have to dig around for a better, old-fashioned, non-compliant container.
其他回答
在向量和列表的情况下,对我来说,主要的区别如下:
向量
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.
因此,记住这些区别,我们通常会考虑内存、频繁的随机访问和插入来决定给定场景中向量和列表的胜者。
std::list的一个特殊功能是拼接(将列表的一部分或整个链接或移动到另一个列表中)。
或者如果你的内容复制非常昂贵。在这种情况下,使用列表对集合进行排序可能更便宜。
还要注意,如果集合很小(并且复制内容的开销不是特别大),即使在任何地方插入和删除,vector的性能也可能优于list。列表单独分配每个节点,这可能比移动几个简单的对象要昂贵得多。
我不认为有什么严格的规定。这取决于您最想对容器做什么,以及您希望容器有多大以及所包含的类型。vector通常优于list,因为它将其内容分配为单个连续块(它基本上是一个动态分配的数组,在大多数情况下,数组是保存一堆东西的最有效方式)。
基本上,vector是一个具有自动内存管理功能的数组。数据在内存中是连续的。试图在中间插入数据是一项代价高昂的操作。
在列表中,数据存储在不相关的内存位置。在中间插入数据并不需要复制一些数据来为新数据腾出空间。
为了更具体地回答你的问题,我将引用这一页
对于访问元素以及从序列末尾添加或删除元素,向量通常是最有效的。对于涉及在末尾以外的位置插入或删除元素的操作,它们的性能不如deques和list,并且迭代器和引用的一致性也不如list。
当你在序列中间有很多插入或删除时。例如,内存管理器。
列表只是stl中double - linkedlist的包装器,因此提供了您可能希望从d-linklist中获得的功能,即O(1)插入和删除。 向量是具有传染性的数据序列,其工作方式类似于动态数组。S-更容易遍历。