By reverse I mean swap the order of the elements so a stack containing ABCD ends up with DCBA. I am currently using vectors instead of stacks just because of the reverse operation.
std::stack<T>
operates by wrapping an underlying container, typically std::deque<T>
.
// According to cppreference.com
template<
class T,
class Container = std::deque<T>
> class stack;
There's no reason to use a std::stack
instead of a std::vector
or a std::deque
unless all you care about is the top element. The structure doesn't even expose iterators, and that's part of the design.
Sure you can write a fancy function to reverse it (store the top, pop, push to a new stack, repeat), but why do more work than you have to?
A stack is a container that provides a nice simple push/pop/top interface. What you are asking for is actually not stack functionality so that implies that a stack is the wrong container for your needs.
Most likely either a vector
or deque
would be a good choice (as you have already mentioned in your question) as they provide constant time push/pop back capabilities, as well as a linear time reversal ( std::reverse
).
The STL stack is not a container, it's a container adapter ( http://www.cplusplus.com/reference/stack/stack/ ). The underlying container type is passed as an argument to the template, with the default being deque. The short answer to your question is 'no' -- the stack interface doesn't provide that capability.
The two options I see are:
Use the stack interface (pure stack solution) as described above (link repeated here for convenience): http://dev-faqs.blogspot.com/2012/02/reverse-given-stack-in-place.html
Use a more flexible structure as you have done (eg vector or deque). In this case it probably makes the most sense to use a deque and push/pop from either end, depending on whether you're using the sequence in "forward" or "reverse" mode. That's most efficient.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.