堆栈在函数中弹出仍然显示在主函数中。调用不应该通过引用给定的向量吗

stack is popped in function still still shows in main function.Isn't the call should be by reference for the vector given

本文关键字:函数 引用 向量 不应该 显示 堆栈 调用      更新时间:2023-10-16

>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访问它只是未定义的行为