Reputation: 101
In C++ STL, Stacks are implemented using container adaptors which rewrite the interface of the Vector class. However, why is it necessary to do the interface rewriting and design a Stack class when there is already the Vector class available? Is it due to cost efficiency i.e. maintaining a stack uses less resources while it could do all necessary jobs?
Upvotes: 2
Views: 906
Reputation: 22350
Why do we need for loops and while loops when we already have goto which is even more powerful? You should adhere to the principle of parsimony - use the least powerful tool that is powerful enough to achieve the desired objective.
If what you need is a stack, take a dependency on the standard library class that provides that functionality, not a more powerful one. It also communicates better to a person reading your code, what you are going to do.
Upvotes: 10
Reputation: 41542
The idea behind the container adaptors was to enforce particular abstract data types on an otherwise open-ended container type. If you have a std::vector
, it's possible to inadvertently insert/erase/access elements in the middle; but if you have a std::stack
you know that won't happen. It's similar to const
: You tell the compiler what restrictions to apply, so that it tells you when you accidentally violate them.
IME, people don't really use stack
and queue
very often. priority_queue
is a little more useful. But in each case, one tends to find the odd special case where you need to break the rules a little, and that means foregoing the overly-principled container adaptors.
Upvotes: 6