'C++ std::set::erase with std::remove_if

This code has the Visual Studio error C3892. If I change std::set to std::vector - it works.

std::set<int> a;
a.erase(std::remove_if(a.begin(), a.end(), [](int item)
{
    return item == 10;
}), a.end());

What's wrong? Why can't I use std::remove_if with std::set?



Solution 1:[1]

std::remove_if re-orders elements, so it cannot be used with std::set. But you can use std::set::erase:

std::set<int> a;
a.erase(10);

Solution 2:[2]

Starting with C++20, you can use std::erase_if for containers with an erase() method, just as Kühl explained.

// C++20 example:
std::erase_if(setUserSelection, [](auto& pObject) {
                                     return !pObject->isSelectable();
                                });

Notice that this also includes std::vector, as it has an erase method. No more chaining a.erase(std::remove_if(... :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juanchopanza
Solution 2 Anonymous