将顶部堆栈元素传输到第二个堆栈的第一个

Transferring the top stack element to the first of the second stack

本文关键字:堆栈 第二个 第一个 传输 顶部 栈元素      更新时间:2023-10-16

好吧,这是我的问题:我是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;   
}

但是,当它试图运行第一秒函数时,它会执行核心转储。我还没有弄清楚为什么。也许我还没有足够研究堆栈,或者我只是对这个主题一无所知,但是我已经陷入困境了一段时间。

如果有人可以帮助我或给我任何有关我做错什么的提示:)。

您是通过复制传递所有参数。因此,firstRow(a,X);调用后,堆栈a仍然为空,因为在其本地变量上操作的函数=参数也名为a。然后该代码崩溃,因为不允许在空堆栈上调用top。添加这样的功能的引用:void firstRow(stack <int>& a,int X)void firstTosecond(stack <int>& a,stack <int>& b,int X)

相关文章: