堆栈在函数中弹出仍然显示在主函数中。调用不应该通过引用给定的向量吗
stack is popped in function still still shows in main function.Isn't the call should be by reference for the vector given
>stack 在函数中弹出仍然显示在主函数中。
调用不应该通过引用给定的堆栈。
void showstack(stack <int> s) {
while (!s.empty()) {
cout << 't' << s.top();
//stack getting popped
s.pop();
}
}
int main () {
stack <int> s;
s.push(10);
s.push(30);
s.push(5);
s.push(1);
cout << "The stack is : ";
showstack(s);
//The stack should be empty here.
cout << "ns.size() : " << s.size();//size should not get displayed
//top should be empty
cout << "ns.top() : " << s.top();
cout << "ns.pop() : ";
s.pop();
showstack(s);
return 0;
}
该
函数showstack
修改堆栈s
的副本,而不是原始堆栈。要使用原始堆栈,请通过引用传递它。 void showstack(stack <int>& s)
,请注意&
。请确保在返回主堆栈后不要在空堆栈上调用top()
。
调用不应该通过引用给定的堆栈
。
是的,它应该,但你没有。
//The stack should be empty here.
不,当您逐个值将堆栈传递给void showstack(stack <int> s)
时,您操作了它的副本。s
的原始实例保持不变。
如果要在原始文件上运行该功能,请将签名更改为
void showstack(stack <int>& s)
// ^
通过引用传递堆栈。
//size should not get displayed
堆栈大小始终可以显示。
//top should be empty
不,原因与上述相同。
另请注意,top()
没有空表示形式。为空std::stack
访问它只是未定义的行为。
相关文章:
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 类 Referention 中C++回调函数引用非静态函数
- 使用函数引用指向节点的指针删除链表中的节点?
- 解释通过从函数引用返回数组的语法
- "Class1"类"Class2"对象作为私有数据成员。如何通过"Class 2"函数引用"Class1"对象?
- 使用默认构造函数引用成员变量初始化错误
- 无法调用函数引用 c++
- 使用 decltype(this) 获取函数引用
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 从内联函数引用文件静态变量
- Boost::将sigaction函数引用绑定到实例
- 一种比函数引用更有效的方法
- 奇怪的未定义函数引用,函数调用C++不存在
- 是否可以检测绑定成员函数引用的对象是否被删除或销毁
- 构造函数引用参数导致seg错误
- 是否可以使函数模板从函数引用中获取“decltype”
- 无法让 Lua 函数引用"self"
- 如何解析变量和函数引用(Linker & Compiler)?
- 从不同模块调用函数 - 引用错误
- 如何在主函数中连接到数据库,然后从其他函数引用它