I created a simple C++ program to test the behaviour of erase() in C++ vectors.
This is my code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// your code goes here
vector<int> vec;
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
cout << vec[0] << " " << vec[1] << " " << vec[2] << endl;
vec.erase(vec.end());
//vec.erase(vec.begin());
cout << vec.size() << endl;
vec.push_back(12);
vec.push_back(10);
cout << vec[0] << " " << vec[1] << " " << vec[2] << endl;
return 0;
}
The problem is the above code is giving segmentation fault when trying to erase the last element from the vector. But when I erase the first element using begin(), it is working fine. I am unable to understand the reason behind it. Any help would be highly appreciated.