我的代码中不断出现分段错误错误
标题
#ifndef DUALSTK
#define DUALSTK
#include <deque>
using namespace std;
enum stackNumber {One, Two};
template <typename T>
class dualStack {
public:
// constructor. set counts to 0
dualStack() : dualStackElements(20, 0) {}
void push(const T& item, stackNumber n);
void pop(stackNumber n);
T& top(stackNumber n);
//const T& top(stackNumber n) const;
bool empty(stackNumber n) const;
int size(stackNumber n) const;
int getCount1() const {return count1;}
int getCount2() const {return count2;}
private:
deque<T> dualStackElements;
int count1, count2;
};
#endif // DUALSTK
主文件
#include <iostream>
#include <deque>
#include "dualstk.h"
using namespace std;
template <typename T>
T& dualStack<T>::top(stackNumber n) {
int num = 0;
if (n == 0) {
num = count1 - 1;
return num;
}
if (n == 1) {
num = 20 - count2;
return num;
}
}
template <typename T>
void dualStack<T>::push(const T& item, stackNumber n) {
if (n == 0) {
count1++;
dualStackElements[top(One)] = item;
}
if (n == 1) {
count2++;
dualStackElements[top(Two)] = item;
}
}
template <typename T>
void dualStack<T>::pop(stackNumber n) {
int item = 0;
int item2 = 0;
if (n == 0) {
item = dualStackElements[top(One)];
cout << item << " ";
count1--;
}
if (n == 1) {
item2 = dualStackElements[top(Two)];
cout << item2 << " ";
count2--;
}
}
template <typename T>
bool dualStack<T>::empty(stackNumber n) const {
return 1;
}
int main() {
dualStack<int> stack;
for(int i = 1; i < 21; i++) {
if(i % 2 == 0) {
stack.push(i, One);
}
else {
cout << i;
stack.push(i, Two);
}
}
cout << endl;
for (int j = 0; j < 10; j++)
stack.pop(One);
cout << endl;
for (int i = 0; i < 10; i++)
stack.pop(Two);
cout << endl;
cout << stack.getCount2();
cout << stack.getCount1();
cout << endl;
cout << "\n" << stack.top(One);
cout << stack.top(Two) << endl;
return 0;
}
每当我的 stack.pop 有一个循环时,它都会正常工作,但如果我在使用一个循环后立即执行 for 循环,则它不会工作
我不确定我做错了什么
for (int j = 0; j < 10; j++)
stack.pop(One);
for (int i = 0; i < 10; i++)
stack.pop(Two);