How can I print out the contents of std::stack and

2019-04-07 12:35发布

In c++ how can I print out the contents of my stack and return its size?

std::stack<int>  values;
values.push(1);
values.push(2);
values.push(3);

// How do I print the stack?

标签: c++ stack
4条回答
乱世女痞
2楼-- · 2019-04-07 13:15

http://www.cplusplus.com/reference/stl/stack/ for the size it's easy use :

cout << mystack.size();

For the rest i didn't see anything about in the doc but you should print the content of your stack when you push it, or have a list with it to keep a record of the element just in order to print it, don't forget to delete it when you're done testing

查看更多
孤傲高冷的网名
3楼-- · 2019-04-07 13:20

The only way to print the elements of a std::stack without popping them, is to write an adapter that extends std::stack (here's an example). Otherwise, you should replace your stack with a std::deque.

查看更多
戒情不戒烟
4楼-- · 2019-04-07 13:20

Both std::stack and std::queue are wrappers around a general container. That container is accessible as the protected member c. Using c you can gain efficient access to the elements; otherwise, you can just copy the stack or queue and destructively access the elements of the copy.

Example of using c:

#include <iostream>     // std::wcout, std::endl
#include <stack>        // std::stack
#include <stddef.h>     // ptrdiff_t
using namespace std;

typedef ptrdiff_t   Size;
typedef Size        Index;

template< class Elem >
Size nElements( stack< Elem > const& c )
{
    return c.size();
}

void display( stack<int> const& numbers )
{
    struct Hack
        : public stack<int>
    {
        static int item( Index const i, stack<int> const& numbers )
        {
            return (numbers.*&Hack::c)[i];
        }
    };

    wcout << numbers.size() << " numbers." << endl;
    for( Index i = 0;  i < nElements( numbers );  ++i )
    {
        wcout << "  " << Hack::item( i, numbers ) << endl;
    }
}

int main()
{
    stack<int>  numbers;
    for( int i = 1;  i <= 5;  ++i ) { numbers.push( 100*i ); }

    display( numbers );
}
查看更多
We Are One
5楼-- · 2019-04-07 13:21

You could make a copy of the stack and pop items one-by-one to dump them:

#include <iostream>
#include <stack>
#include <string>

int main(int argc, const char *argv[])
{
    std::stack<int> stack;
    stack.push(1); 
    stack.push(3); 
    stack.push(7); 
    stack.push(19); 

    for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
        std::cout << dump.top() << '\n';

    std::cout << "(" << stack.size() << " elements)\n";

    return 0;
}

Output

19
7
3
1
(4 elements)

See it live here: http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f

查看更多
登录 后发表回答