简体   繁体   English

哪种STL容器最能满足这些需求?

[英]Which STL container best meets these needs?

I would like some advice on which STL container best meets the following needs: 我想就哪个STL容器最符合以下需求提出一些建议:

  1. The collection is relatively short-lived. 该系列的寿命相对较短。
  2. The collection contains pointers. 该集合包含指针。
  3. Elements are added only at the end. 元素仅在末尾添加。 The order of elements must be maintained. 必须保持元素的顺序。
  4. The number of elements is unknown and may vary from hundreds to millions. 元素的数量是未知的,可能从数百到数百万不等。 The number is known only after the final element is added. 只有在添加最终元素后才能知道该数字。
  5. I may iterate over the elements several times. 我可能会多次迭代这些元素。
  6. After all elements are added, I need to sort the collection, based on the objects the pointers refer to. 添加完所有元素后,我需要根据指针引用的对象对集合进行排序。
  7. After sorting, I may iterate over the elements several more times. 排序后,我可能会多次迭代这些元素。
  8. After that, the collection will be destroyed. 之后,该集合将被销毁。

Thread safety is not required. 不需要螺纹安全。

Here are my thoughts: 这是我的想法:
list: Requires a separate allocation for each element. list:需要为每个元素单独分配。 More expensive traversal. 更昂贵的遍历。
vector: Need to be reallocated as the collection grows. vector:需要在集合增长时重新分配。 Best sort and traversal performance. 最好的排序和遍历性能。
deque: Fewer allocations than list and fewer reallocations than vector. deque:分配比列表少,重新分配少于向量。 I don't know about behavior with respect to sort. 我不知道有关排序的行为。

I am currently using list. 我目前正在使用列表。 The flowchart at In which scenario do I use a particular STL container? 在哪种情况下我使用特定的STL容器的流程图 leads me to deque. 引领我走向deque。

My knowledge of STL is old; 我对STL的了解很早; I don't know about container types that have been added since 2003, so maybe there's something well-suited that I've never heard of. 我不知道自2003年以来添加的容器类型,所以也许有一些我从未听说过的适合的东西。

std::vector<T*> will be the winner based on the points discussed. std::vector<T*>将根据讨论的要点获胜。

Don't be afraid of the resizing that will need to occur--just reserve() a reasonable amount (say 500 if many of your collections will be around there). 不要害怕需要调整大小 - 只需reserve()一个合理的数量(如果你的许多收藏品都在那里,那就说500)。

Sorting performance with vector<T*> will also be very good. 使用vector<T*>对性能进行排序也非常好。

Allocation and deallocation of each T will be important. 每个T分配和释放都很重要。 Pay attention to this. 注意这一点。 For example you may want to allocate thousands of T s at a time, to reduce the memory allocation overhead (and make it faster to deallocate everything at the end). 例如,您可能希望一次分配数千个T s,以减少内存分配开销(并使其更快地在最后解除分配所有内容)。 This is known as an "arena" or "pool". 这被称为“竞技场”或“游泳池”。 You can probably store 32-bit relative pointers into the arena, saving half the pointer storage space. 您可以将32位相对指针存储到竞技场中,从而节省一半的指针存储空间。

And of course, if T is small you might consider storing it by value instead of by pointer. 当然,如果T很小,你可以考虑按值而不是指针存储它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM