首页 > 解决方案 > 将顶部堆栈元素转移到第二个堆栈的第一个

问题描述

好的,这是我的问题:我是 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++stack

解决方案


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


推荐阅读