using the erase ()

Evening everyone

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, const unsigned& M)
{
for (unsigned int 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?

thanks
I am trying to iterate through a list, find the element I want to remove and remove it.

Isn't what you're trying to do just L.remove(*name); ?

It's unclear from the description what 'M' stands for

This is the josephus problem. M is the passed in value, it stands for the Mth person.
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
So what would you suggest I do so I am able to follow the syntax for erase. If I don't use the tmp iterator and I do the argument:

L.erase(name) because it needs an iterator not just a reference.

EDIT:

I was thinking what if I created the function just to return name;

If I did that how would I invoke the return value in my int main using the erase function?
Last edited on
Topic archived. No new replies allowed.