使用 C++ 中定义的堆栈stl
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
stack::pop
是一个 < code>void 函数,它只是丢弃堆栈顶部的元素,以便获取您想要使用的值stack::top
。这样做的原因是异常安全原因(如果返回的对象抛出异常会发生什么其复制构造函数中的异常?)。
stack::pop
is avoid
function which just discards the top element on the stack, in order to get the value you want to usestack::top
.The reason this is so is for exception safety reasons (what happens if the object returned throws an exception in its copy constructor?).
有点挑剔,你的 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.
您正在处理 pop() 这是一个打印到标准输出的操作。流行音乐()
只是从堆栈中删除最顶层的元素。然而最令人困惑的是
是你的调试输出。
我用标准 GNU C++ 编译器编译了你的代码片段
这给了我:
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: