In article <11**********************@l75g2000hse.googlegroups .com>,
gr****@barnholt.net wrote:
This small piece of code is troubling me.. is there anything wrong
with it??
After calling this method the contents ot the input vector are
completely screwed..
(CCountedCIG_CountZero() applies only to a few elements in the vector)
void UElementVector::ClearZeroCountElements(vector<CCou ntedCIG*>
&ioItemVec)
{
vector<CCountedCIG*>::iterator new_end = remove_if(ioItemVec.begin(),
ioItemVec.end(), CCountedCIG_CountZero());
for (vector<CCountedCIG*>::iterator it = new_end; it !=
ioItemVec.end(); it++)
{
delete *it;
*it = NULL;
}
ioItemVec.erase(new_end, ioItemVec.end());
}
<nodThe problem is that remove_if works just by overwriting elements
that no longer belong in the sequence. It doesn't swap them to the end.
What is most likely happening is that you are overwriting the pointers
you want to delete. And then you are deleting copies of the pointers
you want to keep. A subsequent dereference leads to a crash.
You could do a two-pass operation where the first pass did:
1. Check if you want to delete, and if so:
2. delete
3. null pointer
transform could possibly be employed for the first pass.
And then the second pass could call remove (if null pointer).
Or you could write your own algorithm which combines these passes into a
single pass.
-Howard