vector - 我正在尝试使用堆栈打印数字序列的反转。堆栈是使用 Vector 实现的。但我得到分段错误
问题描述
你能帮我找出使用向量实现的堆栈打印反向序列的错误吗?
我遇到了分段错误
#include <iostream>
#include<vector>
using namespace std;
class stack{
public :
int top;
vector<int> data;
bool isempty(){return top == -1;}
void push(int x){data[++top] = x;}
void pop(){--top;}
int topper(){return data[top];}
};
int main()
{
stack s;
int n;
s.top = -1;
cout << "enter the number of integers" << endl;
cin >> n;
for(int i =0; i < n; i ++){
s.push(i);
}
while(!s.isempty()){
cout << s.topper();
s.pop();
}
return 0;
}
解决方案
出现这个问题,是因为a默认vector
有size = 0
。
您可以在向其中添加值之前调整向量的大小,如下所示:
#include <iostream>
#include<vector>
using namespace std;
class stack {
public:
int top;
vector<int> data;
bool isempty() { return top == -1; }
void push(int x) { data.resize(++top+1); data[top] = x; }
void pop() { --top; }
int topper() { return data[top]; }
};
int main()
{
stack s;
int n;
s.top = -1;
cout << "enter the number of integers" << endl;
cin >> n;
for (int i = 0; i < n; i++) {
s.push(i);
}
while (!s.isempty()) {
cout << s.topper();
s.pop();
}
return 0;
}
或者您可以使用内置功能vectors
,我认为这是更好的解决方案:
#include <iostream>
#include<vector>
using namespace std;
class stack {
public:
vector<int> data;
bool isempty() { return data.size() == 0; }
void push(int x) { data.push_back(x); }
void pop() { data.pop_back(); }
int topper() { return data.back(); }
};
int main()
{
stack s = stack();
int n;
cout << "enter the number of integers" << endl;
cin >> n;
for (int i = 0; i < n; i++) {
s.push(i);
}
while (!s.isempty()) {
cout << s.topper();
s.pop();
}
return 0;
}
推荐阅读
- c++ - 带有向量的类构造函数中的析构函数调用
- jquery - Bootstrap datetimepicker第一次点击触发onChange事件?
- css - 如何将用户屏幕宽度的 CSS 变量放入 calc 函数中?
- spring - Spring hibernate JPA 一对多映射:重复键错误
- angular - Angular - 按钮滚动到顶部
- html - 我的下拉按钮出现在搜索栏后面
- binary-decision-diagram - 使用 CUDD/DDDMP 包将 BDD 存储在文件中?
- r - 如何修复,在 ggplot 上使用 2 y 图形绘制图形时,Geom_point 工作但 geom_line 不工作?
- python - 尝试在 VSCode 中使用 boto3 python 3.7 创建 lambda 函数时出现“AttributeError:模块'boto3'没有属性'client'”错误
- hugo - Hugo 帖子目录出现在主页上,但不是帖子