C++ 使用两个附加堆栈反转堆栈

C++ Reversing a stack using two additional stacks

我正在尝试使用其他两个堆栈(S1 和 S2)来反转堆栈 (S)。这是我正在尝试的代码:

#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;
}

这是我每次从 push 中调用 pop 时得到的错误 (x3)。 - stack.cc:14:11: 错误:对 'const value_type' 类型(又名 'const int')的引用无法绑定到 'void' S1.push(S.pop());[=12 类型的右值=]

我试过将弹出的值赋给一个变量,然后用那个变量调用 push,但也没有成功。

如有任何帮助,我们将不胜感激!

pop() 不会 return 从堆栈弹出的值。 pop() return 一个 voidpop() 从堆栈中删除值,不执行任何其他操作。

你需要读取栈顶的值,使用top(),然后调用pop().

你应该写

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

std::stack::pop() 有一个 void return 类型。