执行堆栈的程序以 "code=3221225477" 退出

Program implementing stack exits with "code=3221225477"

该程序只是一个简单的堆栈实现,不断弹出直到堆栈为空。它弹出最后一个字母然后崩溃;虽然,从技术上讲,它做了它应该做的事情。我只想知道为什么我会收到错误代码 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;
}

注:

每当您尝试访问堆栈的元素时都要小心,就像这里:

cout << "Top element is: " << s.top() << endl;

目前,这不是问题,因为堆栈中有项目,但如果在调用此行时堆栈为空,则会出现未定义行为。