繁体   English   中英

将顶部堆栈元素转移到第二个堆栈中的第一个元素

[英]Transferring the top stack element to the first of the second stack

好的,这是我的问题:我是 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 函数时,它会进行核心转储。 我还是没弄明白为什么。 也许我对堆栈的研究还不够,或者我只是对这个主题一无所知,但我已经被困在这部分上很长一段时间了。

如果有人可以帮助我或给我任何关于我做错了什么的提示,我将不胜感激:)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM