简体   繁体   English

为什么std :: stack默认使用std :: deque?

[英]Why does std::stack use std::deque by default?

Since the only operations required for a container to be used in a stack are: 由于在堆栈中使用容器所需的唯一操作是:

  • back() 背部()
  • push_back() 推回()
  • pop_back() pop_back()

Why is the default container for it a deque instead of a vector? 为什么它的默认容器是deque而不是vector?

Don't deque reallocations give a buffer of elements before front() so that push_front() is an efficient operation? 不要deque重新分配在front()之前给出元素缓冲区,以便push_front()是一个有效的操作吗? Aren't these elements wasted since they will never ever be used in the context of a stack? 这些元素不会浪费,因为它们永远不会在堆栈的上下文中使用吗?

If there is no overhead for using a deque this way instead of a vector, why is the default for priority_queue a vector not a deque also? 如果没有以这种方式使用双端队列而不是向量的开销,为什么priority_queue的默认值也不是deque的向量? (priority_queue requires front(), push_back(), and pop_back() - essentially the same as for stack) (priority_queue需要front(),push_back()和pop_back() - 基本上与堆栈相同)


Updated based on the Answers below: 根据以下答案进行了更新:

It appears that the way deque is usually implemented is a variable size array of fixed size arrays. 似乎deque通常实现的方式是固定大小数组的可变大小数组。 This makes growing faster than a vector (which requires reallocation and copying), so for something like a stack which is all about adding and removing elements, deque is likely a better choice. 这使得增长速度比矢量(需要重新分配和复制)更快,因此对于类似于添加和删除元素的堆栈之类的东西,deque可能是更好的选择。

priority_queue requires indexing heavily, as every removal and insertion requires you to run pop_heap() or push_heap(). priority_queue需要大量索引,因为每次删除和插入都需要运行pop_heap()或push_heap()。 This probably makes vector a better choice there since adding an element is still amortized constant anyways. 这可能使得向量成为更好的选择,因为添加元素仍然是分摊常数。

As the container grows, a reallocation for a vector requires copying all the elements into the new block of memory. 随着容器的增长,向量的重新分配需要将所有元素复制到新的内存块中。 Growing a deque allocates a new block and links it to the list of blocks - no copies are required. 增加deque会分配一个新块并将其链接到块列表 - 不需要复制。

Of course you can specify that a different backing container be used if you like. 当然,如果您愿意,可以指定使用不同的后备容器。 So if you have a stack that you know is not going to grow much, tell it to use a vector instead of a deque if that's your preference. 因此,如果你有一个你知道不会增长太多的堆栈,请告诉它使用向量而不是deque,如果这是你的偏好。

See Herb Sutter's Guru of the Week 54 for the relative merits of vector and deque where either would do. 请参阅Herb Sutter的第54周大师,了解vector和deque的相对优点。

I imagine the inconsistency between priority_queue and queue is simply that different people implemented them. 我认为priority_queue和队列之间的不一致只是不同的人实现了它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM