Monday, January 28, 2019

c++ - Erase all even numbers from vector using find_if





#include 
#include
#include
#include
#include


using namespace std;

bool isEven(int n)
{
return n%2 == 0;
}

int main()
{

srand(time(NULL));

vector myVec;

for(int i = 0; i < 20; i++)
{
myVec.push_back(rand() % 100);
}
while(1)
{

vector::iterator q = std::find_if(myVec.begin(), myVec.end(), isEven);
cout << *q << endl;
if(q == myVec.end())
{
myVec.erase(q);
break;
}
else
myVec.erase(q);
}


return 0;
}


This code is giving segmentation fault. The above code is to remove all the even numbers from the vector using find_if and erase function



Please help. Any help will be highly appreciated.



EDIT: I have edited it to make sure that iterator will be valid always.




Still it is giving segmentation fault.


Answer



When using the erase(it); function the iterator changes so you need to set the iterator again to the new one returned by the erase function.



In your code, you are checking for the end if(q == myVec.end()) and then using erase this will throw an error as.end() does not point to data, and to be able to erase an item from the vector the iterator needs to be valid. So by changing if(q == myVec.end()) to if(q == (myVec.end()-1)) it will allow you to delete the last element in case of been a pair.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...