0

I'm trying to reverse a stack (S) using two other stacks (S1 and S2). This is the code I'm trying:

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<int> S, S1, S2;
    S.push(1), S.push(2), S.push(3);

    cout << "The top element of S is: " << S.top() << endl;

    while (!S.empty()) {
        S1.push(S.pop()); 
    }
    while (!S1.empty()) 
        S2.push(S1.pop()); 
    while (!S2.empty()) 
        S.push(S2.pop()); 

    cout << "The top element of S is now: " << S.top() << endl;

    return 0;
}

This is the error I'm getting (x3) for each time I call pop from inside push. - stack.cc:14:11: error: reference to type 'const value_type' (aka 'const int') could not bind to an rvalue of type 'void' S1.push(S.pop());

I've tried assigning the popped value to a variable and then calling push with that variable, but it was unsuccessful also.

Any help would be appreciated!

Brittany
  • 119
  • 1
  • 10
  • 2
    You might want to read some reference documentation before using any library functions: [`std::stack::pop()`](http://en.cppreference.com/w/cpp/container/stack/pop) returns `void`. Another thing is that you don't really need two stacks to reverse a stack. Also, a thing that might go weird is the misuse of the [comma operator](http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work). Make sure you are ready to proceed to the coding by taking a C++ refresher from a [verified source](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Ivan Aksamentov - Drop Apr 10 '16 at 03:26

2 Answers2

4

You should write

 S1.push(S.top());
 S.pop();

std::stack::pop() has a void return type.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

pop() does not return the value popped from the stack. pop() returns a void. pop() removes the value from the stack, and does nothing else.

You need to read the value at the top of the stack, using top(), and then call pop().

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148