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
I am not after solving the problem like Ref1, Ref2 but realizing the cause of the problem and whether I have done something wrong.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With