该程序只是一个堆栈的简单实现,不断弹出直到堆栈为空。 它弹出最后一个字母,然后崩溃; 不过,技术上来说,它做的是它应该做的。 我只想知道为什么我会得到错误代码3221225477,以及如何修复它。 我肯定是很简单的事。
#include <iostream>
#include <stack>
using namespace std;
//Stack implementation in C++ using stack library
int main()
{
stack<string> s;
s.push("A"); //Insert "A" in the stack
s.push("B"); //Insert "B" in the stack
s.push("C"); //Insert "C" in the stack
s.push("D"); //Insert "D" in the stack
//Returns the number of elements present in the stack
cout << "Stack size is " << s.size() << endl;
//Prints the top of the stack ("D")
cout << "Top element is: " << s.top() << endl;
while (!s.empty())
{
cout << "Popping " << s.top() << endl;
s.pop();
cout << "Top element is now " << s.top() << endl;
cout << "The stack size is now " << s.size() << endl;
}
return 0;
}
在这里,如果当前元素是最后一个元素,则pop()
,然后使用没有元素的堆栈访问top()
。
cout << "Popping " << s.top() << endl;
s.pop();
cout << "Top element is now " << s.top() << endl;
cout << "The stack size is now " << s.size() << endl;
至
cout << "Popping " << s.top() << endl;
s.pop();
if (!s.empty()) {
cout << "Top element is now " << s.top() << endl;
cout << "The stack size is now " << s.size() << endl;
}