Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

c++ - Is there a better alternative to std::remove_if to remove elements from a vector?

The task of removing elements with a certain property from a std::vector or other container lends itself to a functional style implementation: Why bother with loops, memory deallocation and moving data around correctly?

However the standard way of doing this in C++ seems to be the following idiom:

std::vector<int> ints;
...
ints.erase(
    std::remove_if(ints.begin(), 
                   ints.end(),
                   [](int x){return x < 0;}),
    ints.end());

This example removes all elements less than zero from an integer vector.

I find it not only ugly but also easy to use incorrectly. It is clear that std::remove_if cannot change the size of the vector (as its name would suggest) because it only gets iterators passed. But many developers, including myself, don't get that in the beginning.

So is there a safer and hopefully more elegant way to achieve this? If not, why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I find it not only ugly but also easy to use incorrectly.

Don't worry, we all did at the start.

It is clear that std::remove_if cannot change the size of the vector (as its name would suggest) because it only gets iterators passed. But many developers, including myself, don't get that in the beginning.

Same. It confuses everyone. It probably shouldn't have been called remove_if all those years ago. Hindsight, eh?

So is there a safer and hopefully more elegant way to achieve this?

No

If not, why?

Because this is the safest, most elegant way that preserves performance when deleting items from a container in which deleting an item invalidates iterators.

anticipating:

Anything I can do?

Yes, wrap this idiom into a function

template<class Container, class F>
auto erase_where(Container& c, F&& f)
{
    return c.erase(std::remove_if(c.begin(), 
                                  c.end(),
                                  std::forward<F>(f)),
                   c.end());    
}

The call in the motivating example then becomes:

auto is_negative = [](int x){return x < 0;};
erase_where(ints, is_negative);

or

erase_where(ints, [](int x){return x < 0;});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...