C++ Logo

std-proposals

Advanced search

[std-proposals] Floating an idea: unstable_remove_if and friends

From: Ted Lyngmo <ted_at_[hidden]>
Date: Thu, 30 Jan 2025 20:34:45 +0100
Hi!

I have an idea for a set of "unstable" erase/remove algorithms that will
move at most as many elements for which the predicate returns true.

I wrote them for my own needs some years ago and use them whenever I
don't care about in what order the remaining elements are since it's
much faster to make as few moves as possible than to move all elements
after a removed element.

Here's a small demo with strings where the two first elements are
erased, which requires 2 moves with `unstable_erase_if` and 23 moves
with `std::erase_if`:
https://godbolt.org/z/5Pd4Wj37T

I've also shared the idea with the Beman project:
> https://discourse.bemanproject.org/t/help-getting-started-writing-a-propsal-for-unstable-remove-and-friends-wanted/335

I'm seeing it as a pure library add-on that can be implemented using
existing features. My own implementation does not cover more than the
basic `unstable_remove_if` algorithm, `unstable_remove` and
`unstable_erase_if` for `std::vector` and `std::string` right now, but
I'll be adding `unstable_erase_if`s for the rest of the C++26 containers
for which there is a `std::erase_if` if needed to make a proper proposal.

I think it'd be nice to have an alternative whenever `std::remove_if` is
used today. "Do I really need the order to be preserved?" If the answer
is "no", `unstable_remove_if` would provide a cheaper alternative.

Would this be worth trying to get into the standard library? I'd be very
happy to get your feedback!

Kind regards,
Ted Lyngmo

Received on 2025-01-30 19:34:50