#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/