19

If I do not to want to create a new container in order to do so?

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
Qiang Li
  • 10,593
  • 21
  • 77
  • 148
  • Check out my answer below. I used the following "standard" hack to get the underlying container of std::stack and std:queue: http://stackoverflow.com/questions/1185252/is-there-a-way-to-access-the-underlying-container-of-stl-container-adaptors – Khaled Alshaya Dec 23 '10 at 23:34

8 Answers8

16

I've written a snippet to do that for debugging. For example:

std::stack<int> s; // works with std::queue also!
s.push(1);
s.push(2);

std::cout << s; // [ 1, 2 ]

Please forgive me for this hackish code! but this is what I've written months ago:

#include <stack>
#include <queue>
#include <ostream>

template <class Container, class Stream>
Stream& printOneValueContainer
    (Stream& outputstream, const Container& container)
{
    typename Container::const_iterator beg = container.begin();

    outputstream << "[";

    while(beg != container.end())
    {
        outputstream << " " << *beg++;
    }

    outputstream << " ]";

    return outputstream;
}

template < class Type, class Container >
const Container& container
    (const std::stack<Type, Container>& stack)
{
    struct HackedStack : private std::stack<Type, Container>
    {
        static const Container& container
            (const std::stack<Type, Container>& stack)
        {
            return stack.*&HackedStack::c;
        }
    };

    return HackedStack::container(stack);
}

template < class Type, class Container >
const Container& container
    (const std::queue<Type, Container>& queue)
{
    struct HackedQueue : private std::queue<Type, Container>
    {
        static const Container& container
            (const std::queue<Type, Container>& queue)
        {
            return queue.*&HackedQueue::c;
        }
    };

    return HackedQueue::container(queue);
}

template
    < class Type
    , template <class Type, class Container = std::deque<Type> > class Adapter
    , class Stream
    >
Stream& operator<<
    (Stream& outputstream, const Adapter<Type>& adapter)
{
    return printOneValueContainer(outputstream, container(adapter));
}

You can stream std::stack and std::queue just like any other supported type!

Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
  • I know VC++'s implementation has a public field for the underlying container, but I'm not sure it's portable... – Etienne de Martel Dec 23 '10 at 23:49
  • 2
    Good note, but the code is actually standard and doesn't depend on a particular implementation. The standard says that the underlying container is `protected`! The way this code works is that it inherits std::stack(or std::queue) then it exposes the underlying container. Please, check the comment under the question itself to get an idea. – Khaled Alshaya Dec 23 '10 at 23:55
  • Interesting, I didn't know that. – Etienne de Martel Dec 24 '10 at 19:28
11

You can't iterate through a stack or a queue. In fact, SGI's documentation says this (it's about stack, but it's the same reason for queue):

This restriction is the only reason for stack to exist at all. Note that any Front Insertion Sequence or Back Insertion Sequence can be used as a stack; in the case of vector, for example, the stack operations are the member functions back, push_back, and pop_back. The only reason to use the container adaptor stack instead is to make it clear that you are performing only stack operations, and no other operations.

So, if you really want to do this, you'll have to empty the stack (or queue):

std::stack<Whatever> s;
// ...
while(!s.empty())
{
    Whatever w = s.top();
    std::cout << w;
    s.pop();
}
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
5
ostream & operator<<(ostream & os, stack<double> my_stack) //function header
{
    while(!my_stack.empty()) //body
    {
        os << my_stack.top() << " ";
        my_stack.pop();
    }
    return os; // end of function
}


/*
using this simple overloaded operator function, you're able to print out all the components of a stack by doing a simple cout << your_stack_name;*/
slfan
  • 8,950
  • 115
  • 65
  • 78
Sam
  • 51
  • 1
  • 1
2

It can be easily done using recursion you just need to know when to re-add the next element

For Stack

void print(stack<char> &s)
{
    if(s.empty())
    {
        cout << endl;
        return;
    }
    char x= s.top();
    s.pop();
    print(s);
    s.push(x);
    cout << x << " ";
 }

And this one is For Queue

void print(queue<char> &s,int num)
{
    if(!num)
    {
        cout << endl;
        return;
    }
    char x= s.front();
    s.pop();
    cout << x << " ";
    s.push(x);
    print(s,--num);
}

Good Luck

2

Posting b/c I found this useful for debugging. Pop from original into a temp and then pop from temp back into original:

template <typename T>
void dump_stack(std::stack<T>& stack) {
  std::stack<T> temp;
  while (!stack.empty()) {
    T top = stack.top(); stack.pop();
    std::cout << top << " ";
    temp.push(top);
  }
  while (!temp.empty()) {
    T top = temp.top(); temp.pop();
    stack.push(top);
  }
}
joshbodily
  • 1,038
  • 8
  • 17
1
  1. If you need to do this, then stack or queue is not the correct choice of container.
  2. If you still insist on doing this, the best way is to make a copy and pop elements off of it and print them. I'm not going to suggest another way because there's no point.
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • regarding 1. of course, i do not want only to print out all elements when using the stack or queue. – Qiang Li Dec 23 '10 at 23:29
  • There is no need to mess with the elements, you can get the underlying container with a simple hack. I used the code in my answer for debugging of course. – Khaled Alshaya Dec 23 '10 at 23:36
  • @Qiang Li Please check my comment under the question it self where I refer to the original question where I found the solution. – Khaled Alshaya Dec 23 '10 at 23:44
  • Not at all, what if I want to see the content of a stack at every step inside a loop during the development? – ramgorur Apr 08 '22 at 05:27
1

I've found solution which should work with all implementations (IMO) of std::stack, but unfortunately the stack must use std::vector instead of queue.

template<typename T>
void printStack(const std::stack<T, std::vector<T>>& s)
{
    typedef typename std::stack<T>::const_reference EntryTypeRef;
    typedef std::remove_reference_t<EntryTypeRef> EntryType;

    for(size_t i=0; i < s.size(); ++i)
    {
        EntryType* e = &s.top();
        cout << *(e-i) << endl;
    }
}

std::vector is dynamic array, so we can use pointer arytmetics.

The marked answer to the question assumes, that the stack has field named 'c', I have another solution which would work with std::stack implementation which has container as first field, but its name does not matter:

template<typename T>
void printStack(const std::stack<T>& s)
{
    typedef typename std::stack<T>::container_type Container;

    const auto containerPtr = reinterpret_cast<const Container*>(&s);

    for(auto e : *containerPtr)
        cout << e << endl;
}
baziorek
  • 2,502
  • 2
  • 29
  • 43
1

Try this:

template<typename T, typename C>
struct myStack : std::stack<T, C> {
    typedef std::stack<T, C> Stack;
    using Stack::stack;
    using Stack::c;                   
};

int main() 
{
    myStack<int, std::deque<int>> s;
    s.push(1);
    s.push(2);

    std::deque<int>::iterator it = s.c.begin();
    while (it != s.c.end())
        std::cout << ' ' << *it++;
}

Here we expose underlying container of std::stack as member c.

user2376997
  • 501
  • 6
  • 22