开发者

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
开发者_如何学Python

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 want to retrieve the second element, why do you need stack as representation? The stack is a LIFO representation, so theoretically you don't retrieve second element, just the last one added.

Use other representation, such as @Naveen mentioned.


If you do that, it will no longer be a stack, by definition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜