Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print out the contents of std::stack and return its size?

Tags:

c++

stack

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?
like image 616
John Avatar asked Sep 27 '12 23:09

John


People also ask

How do I display stack elements in CPP?

The display() function displays all the elements in the stack. It uses a for loop to do so. If there are no elements in the stack, then Stack is empty is printed. This is given below.

What should be the return type of size in stack?

The number of elements in the stack is returned, which is a measure of the size of the stack. Hence the function has an integer return type as size is an int value.

How do I view stack elements in STL?

stack::top() function is an inbuilt function in C++ STL, which is defined in <stack> header file. top() is used to access the element at the top of the stack container.


1 Answers

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 );
}
like image 121
Cheers and hth. - Alf Avatar answered Oct 15 '22 13:10

Cheers and hth. - Alf