如果您只需要 STL 集合,那么什么是首选?

发布于 2024-09-10 09:32:16 字数 124 浏览 2 评论 0 原文

我只需要一袋“东西”。它不需要是一个集合、一张地图,甚至不需要有任何特定的顺序。我只需要能够添加内容并对其进行迭代,仅此而已。我不希望它很大,但如果它确实很大,性能也不会很差。

我应该使用什么容器?

I just need a "bag of things". It doesn't need to be a set, a map or even have any particular order. I just need to be able to add things and iterate over it, nothing more. I don't expect it to be very large but it can't get really bad perf if it does.

What container should I use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

み青杉依旧 2024-09-17 09:32:16

该标准建议使用矢量作为默认容器。但赫伯·萨特实际上论证了使用双端队列作为首选

The standard recommends using vector as your default container. But Herb Sutter actually makes a case for using deque as your first choice.

能否归途做我良人 2024-09-17 09:32:16

vector 可能是所有容器中开销最低的。只要你不在中间添加或删除东西。

vector probably has the lowest overhead of all the containers. As long as you are not adding or removing things in the middle.

染火枫林 2024-09-17 09:32:16

默认情况下,使用向量...但是,如果可能的话,不要忘记使用类型间接!

这样做的原因是,如果您只需要迭代,那么您应该能够使用任何一个可用的 STL 容器,并通过 typedef 间接选择它一次。

例如,假设您最初选择一个向量(这是默认选择):

typedef std::vector<MyThing> MyThingContainer ;

然后像往常一样使用容器:

void foo(MyThingContainer & things)
{
    for(MyThingContainer::iterator it = things.begin(),
        itEnd = things.end() ;
        it != itEnd ;
        ++it)
   {
      MyThing & thing = *it ;
      // Do something with that thing
   }
}

这样,有一天您会找到一个列表,或双端队列,或任何比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) :

typedef std::vector<MyThing> MyThingContainer ;

And then use the container as usual :

void foo(MyThingContainer & things)
{
    for(MyThingContainer::iterator it = things.begin(),
        itEnd = things.end() ;
        it != itEnd ;
        ++it)
   {
      MyThing & thing = *it ;
      // Do something with that thing
   }
}

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.

面犯桃花 2024-09-17 09:32:16

std::向量。不需要运算符<

std::vector. Doesn't require an operator<.

南笙 2024-09-17 09:32:16

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文