list<>::const_iterator with list.remove()?

Can values in a list be removed if using a conatant iterator?
1
2
3
4
for ( list<string>::const_iterator Iter = names.cbegin(); Iter != names.cend(); Iter++ )
{
names.remove( *Iter );
}
Yes, since you're not using the iterator to modify the list, you're using the copy of the value that was stored there. If the list itself is not const, it's okay to call list::remove.

However, be aware that once you erase the value that Iter happens to be pointing to, calling Iter++ is invalid.

You could make this safer by rewriting the loop this way

1
2
3
4
for ( list<string>::const_iterator Iter = names.cbegin(); Iter != names.cend();  )
{
    names.remove( *Iter++ ); // make a copy of Iter!
}


but really, names.clear() is much easier to write.
I can't use list::clear because I am only removing certain data from a list.
Does the list shift up when a value is removed?
Example of the memory
1
2
3
[0] = "a"
[1] = "b"
[2] = "c"

list::remove( at 1 )
1
2
[0] = "a"
[1] = "c"


If it does shift, does Iter automatically become a pointer to the same location?
If it points to the same location there is no need to increment Iter. Doing a continue inside the for loop will make the names.end() return a new size.
I can't use list::clear because I am only removing certain data from a list.

You should use list::remove or list::remove_if then: http://www.cplusplus.com/reference/stl/list/remove_if/

Does the list shift up when a value is removed?

yes

If it does shift, does Iter automatically become a pointer to the same location?

No, iter becomes invalid, the program enters undefined behavior on the next iteration of your loop
Topic archived. No new replies allowed.