std::remove_if not working properly

Hey guys, I have a code snippet that looks like the following:

1
2
auto overOneHundred = [](Person& p){return p.getAge() > 100;};
std::remove_if(std::begin(colony), std::end(colony), overOneHundred);


This is supposed to remove people over the age of 100 from the colony of people. Assume Person has a getAge() function that returns their age in integer.

The problem is that the people are never removed from the colony even after their age exceeds 100.
std::remove_if can't change the size of the container because it doesn't have access to it. Instead it puts all elements that should be removed at the end and returns an iterator to where that is so that you can remove them yourself. std::remove/std::remove_if is almost always used in conjunction with the erase function for this reason.

 
colony.erase(std::remove_if(std::begin(colony), std::end(colony), overOneHundred), std::end(colony));

https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom
You're supposed to make use of the value returned by remove_if.
One of the common uses for it is to pass it to the container-specific erase, as shown in the Example section of https://en.cppreference.com/w/cpp/algorithm/remove
Thank you! Kinda new to the STL so this is good to know.
Topic archived. No new replies allowed.