I want to loop through a vector
and remove an item each time. I believe I should use the erase-remove idiom. I believe erase
on a vector
invalidates any of its iterators. If that's the case, how can I use this idiom in a while
loop?
Here's a broken example:
std::vector<int> vec = { 3, 6, 7, 5 };
auto itr = vec.begin();
while (itr != vec.end())
{
// I'll remove a different element each iteration of the loop.
// Hard-coded "7" here for simplicity:
auto position = std::find(vec.begin(), vec.end(), 7);
vec.erase(position);
++itr;
}
Aucun commentaire:
Enregistrer un commentaire