将顶部堆栈元素传输到第二个堆栈的第一个
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;
}
但是,当它试图运行第一秒函数时,它会执行核心转储。我还没有弄清楚为什么。也许我还没有足够研究堆栈,或者我只是对这个主题一无所知,但是我已经陷入困境了一段时间。
如果有人可以帮助我或给我任何有关我做错什么的提示:)。
您是通过复制传递所有参数。因此,firstRow(a,X);
调用后,堆栈a
仍然为空,因为在其本地变量上操作的函数=参数也名为a
。然后该代码崩溃,因为不允许在空堆栈上调用top
。添加这样的功能的引用:void firstRow(stack <int>& a,int X)
,void firstTosecond(stack <int>& a,stack <int>& b,int X)
。
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何在创建自定义迭代器时获得 std::p air 的第一个和第二个?
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 将第二个 GATT 服务添加到 Movesense 容器
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 使第二个类的构造函数成为第一个类中的友元函数
- 为什么第二个代码给出了预期的结果,而第一个代码却没有?
- 为什么第一个代码块产生垃圾值,而第二个代码块将类成员的值相加?
- 打印无序映射的第二个元素,即集合
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 需要使用模板查找数组的第二个最小和最小值
- c++:交换向量中所有元组的第一个和第二个元素
- 将顶部堆栈元素传输到第二个堆栈的第一个
- 函数,返回堆栈的第二个元素,而不更改C++中的堆栈
- 数据结构-在C++中,如果没有pop()函数,我如何返回堆栈的第二个元素