使用 C++ 中定义的堆栈stl

发布于 2024-08-28 09:47:10 字数 381 浏览 4 评论 0原文

#include <stack>
using namespace std;

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
        printf("%d", s.pop());
    }
}

上面的代码有什么问题吗?

错误:

在函数int main()中:在需要整数的地方使用聚合值

#include <stack>
using namespace std;

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
        printf("%d", s.pop());
    }
}

Whats wrong with the code above?

Error:

In function int main(): aggregate value used where an integer was expected

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

赠佳期 2024-09-04 09:47:10

stack::pop 是一个 < code>void 函数,它只是丢弃堆栈顶部的元素,以便获取您想要使用的值 stack::top

这样做的原因是异常安全原因(如果返回的对象抛出异常会发生什么其复制构造函数中的异常?)。

stack::pop is a void function which just discards the top element on the stack, in order to get the value you want to use stack::top.

The reason this is so is for exception safety reasons (what happens if the object returned throws an exception in its copy constructor?).

失去的东西太少 2024-09-04 09:47:10

有点挑剔,你的 for 循环实际上编码了 11 个项目,而不是像你通过简单查看循环计数而想到的 10 个项目。考虑使用 < 11 如果您的意思是要添加 11 个元素。

Minor nitpick, your for loop is actually encoding 11 items and not 10 like you make think from a brief look at the loop count. Consider using < 11 if you mean 11 elements to add.

薄凉少年不暖心 2024-09-04 09:47:10

您正在处理 pop() 这是一个打印到标准输出的操作。流行音乐()
只是从堆栈中删除最顶层的元素。然而最令人困惑的是
是你的调试输出。

我用标准 GNU C++ 编译器编译了你的代码片段
这给了我:

main.cpp|12|错误:void 表达式的使用无效

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
          printf("%i", s.top());
          s.pop();
    }
}

You're treating pop() which is an operation to print to standard output. pop()
just removes the topmost element from the stack. The most confusing thing however
is your debug output.

I compiled your code fragment with the standard GNU C++ compiler
which gave me:

main.cpp|12|error: invalid use of void expression

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
          printf("%i", s.top());
          s.pop();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文