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

标签: vectorsegmentation-faultstackreversefault

解决方案


出现这个问题,是因为a默认vectorsize = 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;
}

推荐阅读