I need help for return second element of stack without pop() ? but I don't know how can I use.
my code :
stack<int> st;
st.push(10);
st.push(20);
st.top(); // return 20
How do can I make this function is return 10 without pop();
Thanks.
P.S. sorry for my English.
I presume you're trying to emulate a stack-based machine?
Here's the only way to do it with std::stack:
stack<int> st;
st.push(10);
st.push(20);
int top = st.top(); // return 20
st.pop();
int second = st.top(); // return 10
st.push(top);
If you want other behavior you'll have to do your own implementation of stack
that has more capabilities.
You can not do that with stack
, as it is supposed to be LIFO, if you want such a behavior use other sequential containers such as vector
, deque
or list
.
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