Thursday, March 22, 2012

C++ Remove Thyself!

Came up against a nasty bug recently...

What do you think the following code does? (You shouldn't need to be a programmer to guess)

std::remove(myArray.begin(), myArray.end(), "cheese");

(this looks hideously over wordy...)

Maybe, remove all the items matching "cheese" between the beginning to the end of the container 'myArray'?

Good guess!  And if you read the docs, you might think that...

What it actually does is shuffle the elements so that there are no items matching "cheese" near the front of the container.  It returns a pointer to the last valid element.

This means you have to do:
std::erase(std::remove(myArray.begin(), myArray.end(), "cheese"), myArray.end());

(wow! they found an even more hideous way to write code!)

There's even a Wikipedia page! Erase-remove idiom
Sounds kind of ominous...

So, if you ever used std::remove, check all your code for this bug!
Enjoy!

No comments: