简体   繁体   English

我应该使用哪个STL容器? C ++

[英]Which STL container should I use? C++

I have a 'list' of objects, from which I want to take object at random position and push it on front of this list. 我有一个对象的“列表”,我想从中随机获取对象并将其推到此列表的前面。 Only this kind of operation will be performed. 只会执行这种操作。 So I don't need a fast access to end of the list, only to it's front and average access to any other place. 因此,我不需要快速访问列表的末尾,只需要访问其他任何地方的前端和平均访问权限。

Which container would be the best for this? 哪个容器最适合这个? I was thinking about std::vector , but I've read that insert operation is not efficient. 我在考虑std::vector ,但我读过insert操作效率不高。 Then I came up with std::deque because of it's fast access to front, but what about efficiency of it's erase at specific position method? 然后我想出了std::deque因为它可以快速访问前面,但是在特定位置方法的erase效率如何呢?

Thanks in advance for help. 在此先感谢您的帮助。

We can give you guidelines, but no definitive answer – you need to benchmark that yourself because it crucially depends on your collection and object size: 我们可以为您提供指导,但没有确定的答案 - 您需要自己进行基准测试,因为它至关重要取决于您的集合和对象大小:

  • For small objects and/or a relatively small collection, std::vector will be faster because even though you need to copy more data, the better random access time (O(1) vs O(n) for std::list ) and the cache locality will dominate. 对于小对象和/或相对较小的集合, std::vector将更快,因为即使您需要复制更多数据,更好的随机访问时间(对于std::list O(1)vs O(n))和缓存局部性将占主导地位。
  • For large objects and/or a large collection, std::list will be faster because although you need O(n) to pick a random object, insertion will be much faster since the copying of many large objects is very slow. 对于大型对象和/或大型集合, std::list会更快,因为虽然您需要O(n)来选择随机对象,但由于许多大型对象的复制速度非常慢,因此插入速度会快得多。

But where exactly the cut-off between these two scenarios lies I cannot say. 但究竟在这两种情况之间的截止位置我不能说。

Furthermore, if you can get away with swapping the elements instead of insertion, this is a no-brainer: always use a std::vector . 此外,如果你可以逃避交换元素而不是插入,这是一个明智的选择:总是使用std::vector

Based on this answer: https://stackoverflow.com/a/471481/1284631 (and also, on this: https://stackoverflow.com/a/471461/1284631 ), I would go for a list. 基于这个答案: https//stackoverflow.com/a/471481/1284631 (以及在此: https//stackoverflow.com/a/471461/1284631 ),我会找一个列表。 It is cheap to append, iterate, insert and remove. 追加,迭代,插入和删除都很便宜。

PS: This depends if the random position is index-based or not (that is, if you know numerically what position, or the object to move to front results through an iteration over the list and testing its properties). PS:这取决于随机位置是否是基于索引的(也就是说,如果您在数字上知道什么位置,或者通过列表上的迭代并测试其属性来移动到前面的对象)。

So: if the position is known without iterating the list, then go for a vector. 所以:如果在没有迭代列表的情况下知道位置,那么去一个向量。 if the position requires iterating over the collection, then go for a list. 如果该位置需要迭代集合,则转到列表。

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

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