Segmentation fault error in hackerrank problem : Vector-Erase

  c++, erase, segmentation-fault

The problem is:-

https://www.hackerrank.com/challenges/vector-erase/problem?h_r=next-challenge&h_v=zen

I wrote the below code:

#include<bits/stdc++.h>
using namespace std;

int main() {
    vector<int> vec;
    int n,a;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a;
        vec.push_back(a);
    }  
    int c,d,e;
    cin>>c;
    vec.erase(vec.begin()+c-1);
    cin>>d>>e;
    vec.erase(vec.begin()+d-1, vec.end()+e);
    
    cout<<vec.size()<<endl;
    for(int i=0; i<vec.size(); i++){
        cout<<vec[i]<<" ";
    }
    return 0;
}

I don’t think that I have done anything unusual, but it is giving me Segmentation fault error while running. I have just started learning c++ and hence, there may by some concept which I am not aware of. Can someone please explain what is wrong with my code.

Source: Windows Questions C++

LEAVE A COMMENT