How come I can't iterate after erasing something? I made sure that the entry I delete wasn't at the end of the vector, as not to pass the end of the vector. Also, each input was different, so I was only erasing one entry.
I don't see why you need a loop in the deletion part. The find() algorithm will return an iterator pointing to the found element, or to sVec.end() if the data was not found. So to delete the requested string you should do:
As you have it right now it will only erase successfully the requested string if the string is the first string in the array.
And to answer your question: Iterators usually become invalid when the underlying collection is changed. You change the collection by removing a string from it and this means that if you want to iterate, you have to start over.
Ok, I fixed it.
I never tried your code, coder777, but you're not iterating through the vector.
Here's what I did:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void eraseVecStr( strVector &v, const std::string i )
{
strVecIter sIter = v.begin();//set iter to the start of the vector
while( sIter != v.end() )
{
if( sIter == find( v.begin(), v.end(), i ) )//if there's a match of element and input
{
v.erase( sIter );//erase element
break;//break ( exit function )
}
++sIter;//iterare if there's no match, to check next element
}
}
find already gives you an iterator that you can pass to erase, so there's no need to perform a find on the entire vector once for each of its elements. If anything, the comparison should be if (*sIter==i)
And that's exactly what find does, so...:
I did do that, but by making the function a bool and returning true if deleted. And then from that, going back into the function, until a false was returned.
If you actually want to remove all matches, you should use remove_if, which does this in linear time (instead of quadratic time, like you have it now).
so, remove_if will iterate through the vector once and remove all that are the same, rather than the way I did it, to call a function until a delete was not made?