首页 > 解决方案 > 无法弄清楚这个堆栈输出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 它不会输出。所以我将它切换为 <= 并且它仍然没有输出乔治。怎么会?

标签: c++

解决方案


这是因为您正在增加i和减少循环中堆栈的大小。

你可以像这样重写你的循环:

while (!custs.empty()) {
    cout << custs.top() << endl;
    custs.pop()
}

推荐阅读