如果您只需要 STL 集合,那么什么是首选?
我只需要一袋“东西”。它不需要是一个集合、一张地图,甚至不需要有任何特定的顺序。我只需要能够添加内容并对其进行迭代,仅此而已。我不希望它很大,但如果它确实很大,性能也不会很差。
我应该使用什么容器?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我只需要一袋“东西”。它不需要是一个集合、一张地图,甚至不需要有任何特定的顺序。我只需要能够添加内容并对其进行迭代,仅此而已。我不希望它很大,但如果它确实很大,性能也不会很差。
我应该使用什么容器?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
该标准建议使用矢量作为默认容器。但赫伯·萨特实际上论证了使用双端队列作为首选。
The standard recommends using vector as your default container. But Herb Sutter actually makes a case for using deque as your first choice.
vector
可能是所有容器中开销最低的。只要你不在中间添加或删除东西。vector
probably has the lowest overhead of all the containers. As long as you are not adding or removing things in the middle.默认情况下,使用向量...但是,如果可能的话,不要忘记使用类型间接!
这样做的原因是,如果您只需要迭代,那么您应该能够使用任何一个可用的 STL 容器,并通过 typedef 间接选择它一次。
例如,假设您最初选择一个向量(这是默认选择):
然后像往常一样使用容器:
这样,有一天您会找到一个列表,或双端队列,或任何比a更好的容器向量,只需更改 typedef 并重新编译,您就可以更改容器的真实类型。
By default, use a vector... But then, if possible, don't forget to use a type indirection!
The reason for that is that if you only need to iterate, then you should be able to use any one of the available STL containers, and choose it once through a typedef indirection.
For example, let's say you'll initially choose a vector (which is the default choice) :
And then use the container as usual :
This way, the day you find a list, or a deque, or whatever is a better container than a vector, just by changing the typedef and recompiling, you'll change the true type of the container.
std::向量
。不需要运算符<
。std::vector
. Doesn't require anoperator<
.std::vector 是一个很好的默认选择。它是一个简单的数据结构,以动态数组的形式实现。元素彼此相邻打包,这是良好的引用位置(有利于缓存)
std::vector is a good default choice. It's a simple data structure, implemented as a dynamic array. The elements are packed next to each other which is good locality of reference (beneficial for caching)