STL deque accessing by index is O(1)?

前端 未结 4 2044
眼角桃花
眼角桃花 2020-12-05 09:13

I\'ve read that accessing elements by position index can be done in constant time in a STL deque. As far as I know, elements in a deque may be stored in several non-contiguo

4条回答
  •  无人及你
    2020-12-05 09:52

    If deque is implemented as a ring buffer on top of std::vector, which reallocates itself when it grows in size, then accessing by index is indeed O(1).

    The standard provides evidence that such implementation was meant--at least it conforms to standard in complexity estimations. Clauses 23.2.1.3/4 and 23.2.1.3/5 require that

    • inserting to the beginning or to the end of a deque require constant time, while insertion to the middle requires linear time of deque's size

    • when erasing elements from the deque, it may call as many assignment operators, as the distance from the elements being erased to the end of the deque is.

    And, of course, you should count on standard requirements instead of your own vision on how containers and algorithms could be implemented.

    NOTE that the standard requires more than these two points listed above. It also poses requirement that the references to elements must stay valid between insertions to the back or front of the deque. This can be satisfied if the ring buffer contains pointers to the actual elements rather than the elements themselves. Anyway, my answer just demonstrates the idea that multiple implementations may satisfy certain requirements.

提交回复
热议问题