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?
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?
http://www.cplusplus.com/reference/stl/stack/ for the size it's easy use :
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
The only way to print the elements of a
std::stack
without popping them, is to write an adapter that extendsstd::stack
(here's an example). Otherwise, you should replace your stack with astd::deque
.Both
std::stack
andstd::queue
are wrappers around a general container. That container is accessible as theprotected
memberc
. Usingc
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
:You could make a copy of the stack and pop items one-by-one to dump them:
Output
See it live here: http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f