我正在尝试使用堆栈打印数字序列的反转堆栈是使用 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;
}

解决方法

出现此问题,因为默认情况下 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;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...