3

I know that stack/queue is container adaptor that use deque as its default underlying container. But why the hassle when we can just use deque as a stack or a queue? And I don't see the situations where we have to use stack/queue with different underlying containers other than deque either. Besides, does a stack/queue (with underlying deque) cost a bit more memory than a deque? (the data structure is more complex so it has to do, right?). If so, then is the difference big if the data is huge?

Edit: Why was this question marked as duplicate and was linked to c++ deque vs queue vs stack ? I didn't ask the difference between deque and queue (as I've already known). I asked why not use a deque as a stack/queue instead of using the class stack/queue, and some other questions regarding memory consumption.

Community
  • 1
  • 1

2 Answers2

4

If you need a stack or a queue, then use the correct container. They are designed to prevent certain operations that would be allowable on a deque, such as adding or removing an element in the middle, or even iterating through the container. Such operations are totally unacceptable in a strict stack or queue implementation.

You might think it's fine to use a deque because you know that you intended to use it as a normal queue. But when somebody else comes along a few years later and your project has grown significantly, it might not be at all obvious to that person. Doing a non-queue operation just because they can to hack around some other issue, your program may inadvertently be broken in subtle ways that could go undetected for weeks, months or years.

paddy
  • 60,864
  • 6
  • 61
  • 103
2

The container adaptors are there for their interface. Yes, you can use std::deque directly instead, but you don't worry about the underlying container for the most part, rather you have a interface (behavior) for a stack/queue. The adaptors adapt a container to give you a certain behavior and it makes it easier to think in terms of the data structure (i.e. stack or queue). For a stack or queue container adaptor, the interface is a restricted subset of what the underlying container provides, this also may prevent errors or using the container in way that wasn't intended.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166