【问题标题】:Transferring the top stack element to the first of the second stack将顶部堆栈元素转移到第二个堆栈的第一个
【发布时间】:2019-03-10 13:54:21
【问题描述】:

好的,这是我的问题:我是 C++ 堆栈的新手,我正在尝试将顶部元素从一个堆栈移动到另一个堆栈。这是我想出的:

#include <iostream>
#include <stack>
using namespace std;

void firstRow(stack <int> a,int X){
for(int i=1;i<=X;i++){
    a.push(i);
}
cout<<"Row 1: ";
for(int i=1;i<=X;i++){
    cout<<a.top()<<" ";
    a.pop();
 }
}

void firstTosecond(stack <int> a,stack <int> b,int X){
int k;
k=a.top();
b.push(k);
cout<<"Row 2: ";
while(!b.empty()){
    cout<<b.top()<<" ";
    b.pop();
}

}

int main() {
int X;
stack <int> a;
stack <int> b;
cout<<"Enter a number:";
cin>>X;
firstRow(a,X);
firstTosecond(a,b,X);

return 0;   
}

但是,当它尝试运行 firstTosecond 函数时,它会进行核心转储。我还没有弄清楚为什么。也许我对堆栈的研究还不够多,或者我只是对这个主题一无所知,但我已经在这方面停留了很长一段时间。

如果有人可以帮助我或就我做错的事情给我任何提示,我们将不胜感激:)。

【问题讨论】:

  • 你的 C++ 书应该有一章解释按值传递参数和按引用传递参数到函数之间的区别。您应该阅读它,直到您弄清楚 main 中的堆栈始终为空的原因,并且firstRow() 只是将值添加到堆栈中,该堆栈在函数返回时立即被销毁,main() 中的a 仍然存在完全是空的,就像往常一样。您的 C++ 书中的另一个有用的章节是解释错误检查的章节,因此在调用 top() 之前,您会知道检查它以确保堆栈不为空。

标签: c++ stack


【解决方案1】:

您正在通过副本传递所有参数。所以firstRow(a,X);调用堆栈后a仍然是空的,因为函数操作自己的局部变量=参数也叫a。然后代码崩溃,因为不允许在空堆栈上调用top。像这样添加对函数的引用:void firstRow(stack &lt;int&gt;&amp; a,int X),void firstTosecond(stack &lt;int&gt;&amp; a,stack &lt;int&gt;&amp; b,int X)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2013-12-26
    • 2020-06-04
    • 1970-01-01
    • 2013-12-12
    相关资源
    最近更新 更多