gpt4 book ai didi

c++ - 用 “code=3221225477”实现程序退出堆栈

转载 作者:行者123 更新时间:2023-12-02 09:52:34 24 4
gpt4 key购买 nike

该程序只是堆栈的简单实现,一直弹出直到堆栈为空。它弹出最后一个字母,然后崩溃;不过,从技术上讲,它可以完成应有的功能。我只想知道为什么我得到错误代码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;
现在,这不是问题,因为堆栈中有项目,但是如果在调用此行时堆栈为空,则可能是行为未定义的情况。

关于c++ - 用 “code=3221225477”实现程序退出堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63286266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com