c++ - 从堆栈弹出值

标签 c++

#include <iostream>
#include <stack>

using namespace std;

int main()
{
     stack<int> S;

     int n, x;

     cout << "Enter number of values that     will be pushed into the stack: ";
     cin >> n;

     for(int i = 1; i < n; i++){
        cout << "Value " << i << ": ";
        cin >> x;
        S.push(x);
     }

     cout << endl;
     cout << "Output: " << endl;

     while(!S.empty()){
          cout << "| ";
          S.pop();
          cout << " |" << endl;
     }
}

大家好。这是我的代码。如果我在堆栈中输入这些值:3、7、2、9、1 并希望像这样显示:

| 1 |
| 9 |
| 2 |
| 7 |
| 3 |

但我最终得到:

|    |
|    |
|    |
|    |
|    |

请帮忙。

最佳答案

使用 S.top() 获取最顶层元素,使用 S.pop() 将其从顶部移除。

#include <iostream>
#include <stack>

using namespace std;

int main()
{
     stack<int> S;

     int n, x;

     cout << "Enter number of values that will be pushed into the stack: ";
     cin >> n;

     for(int i = 1; i < n; i++) {
        cout << "Value " << i << ": ";
        cin >> x;
        S.push(x);
     }

     cout << endl;
     cout << "Output: " << endl;

     while(!S.empty()) {
          /************* Change here ****************/
          cout << "| " << S.top() << " |" << endl;
          S.pop();
     }
}

关于c++ - 从堆栈弹出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58324652/

相关文章:

c++ - 每次选择随机单元格和随机值的数独求解的回溯逻辑

c++ - Android.mk - 包含 OpenCV 目录,用于使用 NDK 进行 native C++ 编译

c++ - 静态变量初始化

c++ - C++ 中的短路评估和赋值

c++ - 禁止后代类 C++ 中的字段

c++ - 无锁数据结构中的非 POD 类型

c++ - 如何使用 auto_ptr 作为处理另一个成员变量的成员变量

c++ - Doxygen - 将参数声明为可选

c++ - 在 Qt 中更改 show() 上的窗口位置

C++、海湾合作委员会 : avoid evaluation of useless expressions