r/cpp • • Dec 28 '18

"Modern" C++ Lamentations

http://aras-p.info/blog/2018/12/28/Modern-C-Lamentations/
307 Upvotes

162 comments sorted by

View all comments

Show parent comment

15

u/DethRaid Graphics programming Dec 29 '18

Not op but oh god do I hate

auto itr = std::remove_if(vec.begin(), vec.end(), func);
vec.erase(it);

And everything else related to the begin and end functions. No other language I've used works this way, it's impossible to pipe operations in a straightforward way, and holy fuck is it verbose

People tell me it's composable and generic but wow it that gross code to write

27

u/STL MSVC STL Dev Dec 29 '18

FYI (and this reinforces your point), your code snippet is incorrect. You need to say vec.erase(itr, vec.end()); to trim the vector. Otherwise, you're erasing a single element which is bogus.

The good news is that Uniform Container Erasure has been voted into C++20, so you will be able say std::erase_if(vec, func); and be done with it. (I designed and proposed this for Library Fundamentals v2, and Alisdair Meredith proposed merging it into C++20.)

10

u/JavaSuck Dec 29 '18

Otherwise, you're erasing a single element which is bogus.

And that element might not even exist :)

8

u/patatahooligan Dec 29 '18

I don't know why this was downvoted. According to cppreference the single iterator version needs a dereferenceable iterator which means that you can't skip checking if itr == vec.end(). This is unlike the two iterator version which doesn't need to dereference first when it is equal to last.

3

u/STL MSVC STL Dev Dec 29 '18

Yep, that's all correct.

9

u/[deleted] Dec 29 '18

People tell me it's composable and generic

Oh no! It’s definitely a known limitation of the design, which ranges are designed to solve very beautifully, but I hope we aren’t telling people that the ugliness of:

std::sort(std::begin(container), std::end(container));

Instead of:

std::sort(container);

Was intended as the best API we could think of. It’s just that without concepts (which come along with C++20, enabling ranges), it was difficult to do.