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?
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.
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.
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.
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With