我应该使用哪个STL容器? C ++ [英] Which STL container should I use? C++

查看:147
本文介绍了我应该使用哪个STL容器? 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.

哪个集装箱是最好的?我正在考虑 std :: vector ,但我已经读过 insert 操作是无效的。然后我想出了 std :: deque 因为它是快速访问前面,但它的效率擦除在特定位置方法?

Which container would be the best for this? I was thinking about std::vector, but I've read that insert operation is not efficient. 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?

感谢您提供帮助。

推荐答案

我们可以给你指导,但没有确定的答案 - 你需要自己进行基准测试,因为它至关重要取决于你的收藏和对象大小:

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:


  • 对于小对象和/或相对小的集合, std :: vector 将更快,因为即使你需要复制更多的数据,更好的随机存取时间(O $ std :: list ),并且缓存位置将占主导地位。

  • 对于大对象和/一个大的集合, std :: list 会更快,因为虽然你需要O(n)选择一个随机对象,插入会更快,因为复制许多大对象是非常缓慢的。

  • 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.
  • 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.

但是在这两种情况之间的界限,我不能说。

But where exactly the cut-off between these two scenarios lies I cannot say.

此外,如果你可以使用交换元素而不是插入,这是一个没有脑子:总是使用 std :: vector

Furthermore, if you can get away with swapping the elements instead of insertion, this is a no-brainer: always use a std::vector.

这篇关于我应该使用哪个STL容器? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆