std::list and std::vector - Best of both worlds?

假装没事ソ 提交于 2020-07-15 17:19:07

问题


By vector vs. list in STL:

  • std::vector: Insertions at the end are constant, amortized time, but insertions elsewhere are a costly O(n).

  • std::list: You cannot randomly access elements, so getting at a particular element in the list can be expensive.

I need a container such that you can both access the element at any index in O(1) time, but also insert/remove an element at any index in O(1) time. It must also be able to manage thousands of entries. Is there such a container?

Edit: If not O(1), some X << O(n)?


回答1:


There's a theoretical result that says that any data structure representing an ordered list cannot have all of insert, lookup by index, remove, and update take time better than O(log n / log log n), so no such data structure exists.

There are data structures that get pretty close to this, though. For example, an order statistics tree lets you do insertions, deletions, lookups, and updates anywhere in the list in time O(log n) apiece. These are reasonably good in practice, and you may be able to find an implementation online.

Depending on your specific application, there may be alternative data structures that are more tailored toward your needs. For example, if you only care about finding the smallest/biggest element at each point in time, then a data structure like a Fibonacci heap might fit the bill. (Fibonacci heaps are usually slower in practice than a regular binary heap, but the related pairing heap tends to run extremely quickly.) If you're frequently updating ranges of elements by adding or subtracting from them, then a Fenwick tree might be a better call.

Hope this helps!




回答2:


Look at a couple of data structures.

  • The Rope
    Tree of arrays. The tree is sorted by array index for fast index search.
  • B+Tree
    Sorted tree of sorted arrays. This thing is used by almost every database ever.

Neither one is O(1) because that's impossible. But they are pretty good.



来源:https://stackoverflow.com/questions/61602789/stdlist-and-stdvector-best-of-both-worlds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!