how to print out all elements in a std::stack or std::queue conveniently

后端 未结 8 1711
忘掉有多难
忘掉有多难 2020-12-14 20:46

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

8条回答
  •  攒了一身酷
    2020-12-14 21:31

    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
    void printStack(const std::stack>& s)
    {
        typedef typename std::stack::const_reference EntryTypeRef;
        typedef std::remove_reference_t 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
    void printStack(const std::stack& s)
    {
        typedef typename std::stack::container_type Container;
    
        const auto containerPtr = reinterpret_cast(&s);
    
        for(auto e : *containerPtr)
            cout << e << endl;
    }
    

提交回复
热议问题