I am currently having a problem with using the erase function. I am trying to iterate through a list, find the element I want to remove and remove it. The thing is, when I go to execute it it runs but I am not removing anything. Can anyone help me find out why this is? My chunk of code is at the bottom.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
LI find_person (list<string>& L,LI& name, constunsigned& M)
{
for (unsignedint i = 0; i > M -1; i++)
{
LI end = L.end();
list<string>::iterator tmp;
// went passed end of list, wrap around to front
if (name == end)
name = L.begin();
// iterate through list
if (name == --end)
name = L.erase(L.begin());
else
name = tmp;
L.erase(tmp);
++name;
return name;
}
}
I know I am passing a reference to a iterator which is why I made a new iterator to take the position so I can use the erase function. Am I going about this all wrong?
That makes the intent a lot clearer.
Obvious problems:
1. The loop is never entered, because M-1 is always greater than 0
2. return statement is inside the loop, so even if you fix the loop controlling condition, you never iterate more than once
2. in that only iteration, you're doing the following, in the typical case where name points at someone in the middle of the list:
a) name is not past-the-end, so line 9 is not executed
b) name is not the last person, so line 12 is not executed
c) so you come to line 14, where the uninitialized iterator tmp is copied into name, destroying its previous contents, and erasing that invalid iterator is undefined behavior