Skip to content

Return removed element count in erase and erase_if #75

@mkurdej

Description

@mkurdej

Disclaimer: if it's not the place to post this type of suggestions, please redirect me to the correct one.

In my opinion, erase and erase_if algorithms added by this TS should return the number of removed elements instead of void.
For instance, std::list::remove and std::list::remove_if (https://en.cppreference.com/w/cpp/container/list/remove) return this count since C++20.

I may be mistaken, but I see no substantial overhead to returnig removed count in erase and erase_if.

For lists and forward_lists, just return c.remove_if(pred); is enough.
For maps, storing old size before the removal, and returning .size() - old_size would be enough.
For vectors and deques, the overhead is minimal and consists in calling std::distance with the iterator resulting from the call to std::remove_if before calling c.erase(...).

I.e. for vectors and deques, it would look like:

template <typename Container, typename Pred>
std::size_t erase_remove_if(Container & c, Pred pred)
{
    const auto last          = std::end(c);
    auto new_last            = std::remove_if(std::begin(c), last, pred);
    const auto removed_count = std::distance(new_last, last);
    c.erase(new_last, last);
    return removed_count;
}

and for node-based containers:

template <typename Container, typename Pred>
std::size_t erase_nodes_if(Container & c, Pred pred)
{
    const std::size_t old_size = std::size(c);

    auto it         = c.begin();
    const auto last = c.end();
    while (it != last)
    {
        if (pred(*it))
        {
            it = c.erase(it);
            assert(last == c.end());
        }
        else
        {
            ++it;
        }
    }

    return old_size - std::size(c);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions