So much of this type of code to fix:
-
So much of this type of code to fix:
for (auto iter = myvector.begin();
iter < myvector.end();
iter ++)
{
if (iter->foo)
{
myvector.erase(iter);
}
}Problems:
1) Don't compare the iter to *less than* end(), it should be compared to end(). Works with std::vector, but only by luck.2) When you erase an item from a vector, you invalidate your iterators!
I'm amazed this codebase got as far as it did. #cpp
-
R relay@relay.infosec.exchange shared this topic on
-
So much of this type of code to fix:
for (auto iter = myvector.begin();
iter < myvector.end();
iter ++)
{
if (iter->foo)
{
myvector.erase(iter);
}
}Problems:
1) Don't compare the iter to *less than* end(), it should be compared to end(). Works with std::vector, but only by luck.2) When you erase an item from a vector, you invalidate your iterators!
I'm amazed this codebase got as far as it did. #cpp
@charette try with a temp vector and add the good elements. Finally copy the tmp vector to myvector
-
@charette try with a temp vector and add the good elements. Finally copy the tmp vector to myvector
@lann I wasn't looking for solutions, I was complaining that this codebase I'm working with is full of serious coding mistakes.
(See my previous posts on this topic.)
-
R relay@relay.mycrowd.ca shared this topic on