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

11,567

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

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

Share:
11,567
Elmi Ahmadov
Author by

Elmi Ahmadov

Google Fan

Updated on June 30, 2022

Comments

  • Elmi Ahmadov
    Elmi Ahmadov almost 2 years

    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.

  • zvrba
    zvrba almost 13 years
    Agreed, he should just use vector. Methods push_back and pop_back are useful to emulate a stack, + he can do a bunch of other useful things. I don't even know why the standard is polluted with the existence of std::stack.
  • Mark Ransom
    Mark Ransom over 8 years
    No one would argue that processors don't have stacks, yet you can access any element of the processor stack at any time (on most popular architectures).