Q:

Segmentation fault on erasing the last element from the vector C++

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.

A:

The problem is that std::vector::end returns an iterator to the element following the last element of the container, not to the last element.
What you want should be
vec.erase(vec.end() - 1); // trying to erase the last element of vec

A:

vec.end() is giving you the iterator to the element following the last element of the container. See here:

Attempting to erase it is undefined behaviour. You should instead erase by doing either:
vec.erase(vec.end() - 1);

or
 vec.erase(vec.begin() + vec.size() - 1);

