c++ - 将顶部堆栈元素转移到第二个堆栈的第一个
问题描述
好的,这是我的问题:我是 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)
.
推荐阅读
- java - java.lang.NoClassDefFoundError: org/junit/jupiter/api/extension/ScriptEvaluationException
- flutter - Flutter Riverpod:需要在更新状态之前从 StateNotifierProvider 获取旧状态
- javascript - 如何使用 JavaScript 从 cookie 中提取价值?
- firebase - [Firebase-OAuth]:如何为回头客访问 GitHub 凭据/访问令牌
- javascript - 不能用身份证封号
- docker - Docker 镜像非常慢
- amazon-web-services - Amazon SNS 在创建账户后不发送短信
- python - 子图 X 轴刻度标签重叠,需要自动设置
- javascript - 有什么方法可以在javascript中加上多数组编号?
- python - 如何获取文件名的每个部分并将其分别插入表中?