erasing element from a list which will traversed

So far I know it's forbidden erasing an element from a list while this list will be traversed. Is this right?
If so, exists there a common workaround for preventing such?

Here an example for emphasizing my problem:
1
2
3
4
5
6
7
8
9
std::vector<int> vec(9);
for( std::size_t i; i < vec.size; ++ i )
{
    if(  vec[i] == 0) {
        vec.erase( vec.begin() + i);
    } else {
        // do something by accessing to vec's elements
    }
}
Last edited on
Be careful chucking around terms like 'list' when your code's showing std::vector. As you might know these are distinct entities in the standard and just creates unnecessary confusion.
it's forbidden erasing an element from a list while this list will be traversed

if the container is not const qualified why is it forbidden?
You are right, it would be better if I had written 'sequence container' instead of 'list'. Sorry for my sloppyness.

The probem is, afaik, that by erasing (or adding) some element the sequence container gets a new size() wihich differs from the size() value in the loop head.
Last edited on
@gunnerfunner Thank you for this link. I guess that I could never elaborate such an elegant solution only by my mind.
One thing I am learning about standard library containers is that there are various ways to iterate over them – the usual C-style size_t based loops, iterators and then, post C++11, range-loops.
While range loops are useful in many contexts one drawback with them is that they lose the iterators and so offer lesser control over the container and its elements than iterators which, I think, are probably the most powerful of the three.
To me, as I'm at a relative beginner level, I've used for almost all cases the std::vector and the c-style for-loops, just because it's easy to understand and gives the index too, which I often miss at the range-for. But, not at least by your link example, I appreciate the iterator solution more and more. Maybe it's a little bit harder to handle, but the most effort (beside full iterator control) is its independence of the container's choice.
Topic archived. No new replies allowed.