Search code examples
c++algorithmstlremove-if

c++ understanding the third argument of `remove_if()`


I'm trying to understand the third argument in the remove_if() algorithm. According to the description it should be removed if the function returns true. However the function does not return a bool. What syntax is [](char c)?

Does remove_if() actually remove the element? If so why would you call erase() afterwards.

std::string S("AA BB-4499--5");
auto newEnd = std::remove_if(S.begin(), S.end(), [](char c){return c == ' ' || c == '-';});
S.erase(newEnd, S.end());

Solution

  • What syntax is [](char c)?

    It is lambda syntax in C++11 and later.

    In this case, it is used as a predicate which remove_if calls to decide which elements to remove.

    Does remove_if() actually remove the element?

    No, it just moves the "removed" elements to the end of the string, and then returns an iterator to the first "removed" element. The subsequent erase() actually removes the elements from the string. This is called the erase-remove idiom.