c++ - 无法弄清楚这个堆栈输出c ++
问题描述
所以我有一个使用堆栈库的教程创建的堆栈示例
stack<string> custs;
custs.push("george");
custs.push("louie");
custs.push("florence");
// cout << "size" << custs.size() << endl;
if (!custs.empty()) {
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
}
我运行它并得到了输出: florence louie
我的问题是为什么它不输出乔治?程序输出顶部数据然后弹出它。这意味着它应该输出 Gorge 然后弹出它。为什么这不会发生?最初代码是 i < cust.size 所以我认为因为 i 不小于 1 它不会输出。所以我将它切换为 <= 并且它仍然没有输出乔治。怎么会?
解决方案
这是因为您正在增加i
和减少循环中堆栈的大小。
你可以像这样重写你的循环:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop()
}
推荐阅读
- python - Django 将计算天数字段与浮点列相乘
- javascript - ASP.Net MVC LabelFor 无法处理回发或页面加载
- java - 如何使用 java 使用 json 中的动态键
- android - 打开应用后Android动态链接意图不清楚
- zebra-printers - ZPL 中心变量文本
- java - 未使用 RSA 加密进行加密的大数据
- angularjs - 当数组中的坐标相同时,Google Maps 热图在图块上返回 404
- dji-sdk - DJI sdk - 示例代码执行语句
- shell - 遍历特定目录中的每个文件
- php - 私有成员变量必须带有下划线前缀