思考如何实施?

发布于 2024-10-07 09:14:05 字数 1431 浏览 3 评论 0原文

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

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

发布评论

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

评论(3

掩耳倾听 2024-10-14 09:14:05

由于这是一个链接列表,您可能应该使用 std::list...

经验法则是,当您需要将元素插入列表中的随机位置或从列表中删除随机元素时,您需要使用链表。如果您主要需要在列表末尾添加/删除元素,那么您应该使用std::vector。如果您需要在列表的开头或结尾添加/删除元素,那么您应该使用std::deque

请记住,我们在这里讨论的是概率。如果您需要千载难逢地将一个元素插入到 std::vector 的中间,那可能没问题。但如果您需要一直这样做,则会对性能产生重大影响,因为向量需要不断移动其元素,并且可能还需要重新分配其内存。

另一方面,使用向量的优点是它的元素在内存中是连续的,如果你只需要因为缓存而按顺序遍历它们,这会大大提高性能。

Since this is a linked list, you should probably use std::list...

The rule of thumb is that you want to use a linked list when you need to insert elements into random positions in the list, or delete random elements from the list. If you mainly need to add/delete elements to/from the end of the list, then you should use std::vector. If you need to add/delete elements to/from either beginning or the end of the list, then you should use std::deque.

Keep in mind, we are talking about probabilities here. If you need to insert an element into the middle of an std::vector once in a blue moon, that will probably be ok. But if you need to do this all the time, it will have a major impact on performance, because the vector will need to constantly move its elements, and probably reallocate its memory too.

On the other hand, the advantage of using a vector is that its elements are contiguous in memory, which greatly improves performance if you simply need to traverse them in order because of caching.

终止放荡 2024-10-14 09:14:05

既然这个列表中的数据是指针,为什么还要使用链表呢?对于小型 POD,std::vector 通常是最好的选择,并且由于其数据的更好的局部性,可以与处理器缓存很好地配合,因此它的性能通常优于链表,即使在理论上,链表应该更好。我会选择 std::vector ,直到某些分析表明存在性能问题并且 std::list 性能更好。

Since the data in this list is pointers, why bother with a linked list at all? For small PODs, std::vector is usually the best first bet, and due to the better locality of its data playing nicely with processor caches it often out-performs a linked list even where, in theory, a linked list should be better. I'd pick std::vector until some profiling would show that there is a performance problem and std::list performs better.

一身软味 2024-10-14 09:14:05

请参阅此处:

http://linuxsoftware.co.nz/cppcontainers.html

有一个流程图帮助您在底部选择合适的容器。

See here:

http://linuxsoftware.co.nz/cppcontainers.html

There's a flow chart to help you choose the right container at the bottom.

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