Блог пользователя maybesomeone

Автор maybesomeone, история, 22 месяца назад, По-английски

is vector better than deque ?. can someone tell what are some things that makes vector better than deque

  • Проголосовать: нравится
  • +11
  • Проголосовать: не нравится

»
22 месяца назад, # |
Rev. 3   Проголосовать: нравится +3 Проголосовать: не нравится

You can push_back() [basically adding elements on the last] on both deque and vector. Deque can pop_front()/push_front() which is basically removing/adding the first element. You can also do this in vector but it will take O(n) to shift the entire vector but deque will take O(1). But you can always have an integer/pointer variable that points to the start of the vector, so when you need to remove an element from the front, just increase the value of the pointer/variable by 1 (adding to the front will still take O(n) and you cant avoid that). Vector also has added benefits of being able to sort elements easily. So Vector is better in my opinion but there are some cases where deque is needed (mainly because using vector in place of deque in this way will mean that size of the vector is equal to or greater than the deque as you aren't actually deleting the element from the vector, and also in cases where you need to add elements in the front). Hope this helps brother!

  • »
    »
    22 месяца назад, # ^ |
      Проголосовать: нравится +6 Проголосовать: не нравится

    i know this and we can also sort deque. my main question is what makes vector better than deque. or is both of them same in terms of time complexity and memory usage

    • »
      »
      »
      22 месяца назад, # ^ |
        Проголосовать: нравится +3 Проголосовать: не нравится

      Oh, I didn't know you can sort deques. In terms of functionality I think deque is faster but it doesn't have built in sorting-upperbounds-lowerbounds-find functions (you have to make them yourself).

»
21 месяц назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

You should read this. This blog has detailed discussion on C++ deque and C++ vector

»
21 месяц назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Deque is very similar to vector in terms of time complexity. The most obvious difference is that deque allows for O(1) push_front/pop_front.

However one noticable difference is that push_back on a vector can invalidate pointers to elements in the vector, but push_back onto a deque will not. This is because vector needs to do reallocation to increase its capacity. On the other hand deque is stored in fixed sized blocks in memory, so it does not need to reallocate.