Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I return second element of stack without pop() function in C++?

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.

like image 753
Elmi Ahmadov Avatar asked Jun 04 '11 04:06

Elmi Ahmadov


2 Answers

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.

like image 89
Mark Ransom Avatar answered Sep 19 '22 11:09

Mark Ransom


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.

like image 45
Naveen Avatar answered Sep 19 '22 11:09

Naveen