Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a runtime error: Vector erase iterator outside range

I have faced with a strange runtime error for the following code:

#include <algorithm>
#include <vector>

using std::vector;

struct Data
{
    int id;
};

int main()
{
    vector<Data> mylist;

    Data m;
    m.id = 10;

    mylist.push_back(m);

    mylist.erase(std::remove_if(
        mylist.begin(),
        mylist.end(),
        [](const Data &m) {
        return m.id>100;
    }));

    return 0;
}

The error says:

Vector erase iterator outside range

Screenshot

I am not after solving the problem like Ref1, Ref2 but realizing the cause of the problem and whether I have done something wrong.

like image 300
Danze Avatar asked Aug 17 '18 04:08

Danze


2 Answers

The correct form is

mylist.erase(
    std::remove_if(mylist.begin(),mylist.end(),lambda),
    mylist.end());

You need to pass the end to the erase too.

like image 141
Arash Avatar answered Nov 18 '22 15:11

Arash


In the above example, the remove_if function template will return an invalid iterator. Now as per the documentation of std::vector::erase the iterator pos must be valid and dereferenceable which is in your case is not valid and because of which the assert message is thrown.

Alternatively, you can just provide the end() iterator as second argument to the std::vector::erase function or use std::vector::pop_back to pop the element from the vector.

like image 27
sonulohani Avatar answered Nov 18 '22 17:11

sonulohani