【发布时间】:2019-11-29 11:27:57
【问题描述】:
使用这段代码,当我尝试将堆栈引用传递给 transferStacks() 方法时,我遇到了分段错误。任何有助于理解为什么会这样的帮助都会有所帮助!
我可以摆脱辅助方法,它应该可以工作,但我试图从概念上理解。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
void transferStacks(stack<int> & s1, stack<int> & s2){
if (s1.empty()){
for (int i = 0; i < s2.size(); i++){
int element = s2.top();
s1.push(element);
s2.pop();
}
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int queries = 0;
cin>>queries;
stack <int> newestOnTop;
stack <int> oldestOnTop;
while (queries!=0){
int type = 0;
cin >> type;
int input = 0;
if (type == 1){ //enqueue
cin>>input;
newestOnTop.push(input);
}
else if (type == 2){ //dequeue
transferStacks(newestOnTop, oldestOnTop);
oldestOnTop.pop();
}
else if (type == 3){ //peek
transferStacks(newestOnTop, oldestOnTop);
cout<<oldestOnTop.top()<<endl;
}
queries--;
}
return 0;
}
分段错误
【问题讨论】:
-
导致分段错误的输入是什么?
标签: c++ reference segmentation-fault stack