2

The C++ standard library tries to have as uniform of an interface as possible for all of its containers. However, one black sheep sticks out:

#include <algorithm>
#include <stack>

int main()
{
    std::stack<int> s;
    std::reverse(std::begin(s), std::end(s));
}

I can't use this common idiom to reverse a container because a stack is not a container: it's an adapter. As a result, it has no begin or end functions.

I would have to do something like this:

std::stack<int> s;
std::stack<int> s2;
while (!s.empty())
{
    s2.push(s.top());
    s.pop();
}
while (!s2.empty())
{
    s2.top(); // do something with it
    s2.pop();
}

What is the "standard" way of doing this? No ad-hoc hacks or convoluted methods, please.

  • 1
    Your code looks good. In the end, just `std::swap(s, s2)`. You can also just use `std::vector` instead of `std::stack` if you need in-place reversing – Niklas B. May 05 '16 at 10:30
  • 1
    [You can use this hacky function to get the container](http://stackoverflow.com/questions/1185252/is-there-a-way-to-access-the-underlying-container-of-stl-container-adaptors). Then you can use `std::reverse` on it. – rozina May 05 '16 at 10:31
  • I would point you to this: http://stackoverflow.com/questions/4115431/inserters-for-stl-stack-and-priority-queue and this: http://stackoverflow.com/questions/1723515/insert-into-an-stl-queue-using-stdcopy – John Zwinck May 05 '16 at 10:32

0 Answers0