January 2008 Archives

STL warts - when removing isn't

| No Comments

Pop quiz: what does the remove function provided in the C++ STL algorithm package do?

Simple question, surely... Your answer? If you said "it removes the value t from the list between the two iterators" then -- bzzzzt, thank you for playing. It doesn't actually remove anything. Quoting from the description:
Reorders the range [first,last) to prepare for erasing all elements of equal value.
So the way to actually erase something from a std::vector: So all it does is shuffle the items to be deleted to the end, and return an iterator to them. Then the erase method from the vector snips them off the end. The above erase/remove line is a standard idiom for actually removing an item by value from a container. This is one of several poorly named methods in the STL. There are other design warts which I'll discuss in future articles.

A subtle bug involving C++ temporaries

I tracked down a subtle little bug the other day. My code was crashing on a line that should never crash (and we've all heard that one before!). It arose from doing two quite innocuous things, but when combined - disaster! I decided to write it up as an example to my 3 readers and Google.