STL list, delete all the odd numbers

前端 未结 4 1367
不知归路
不知归路 2021-01-16 08:27

I am trying to learn how to work with STL and tried to write a function which will recieve a refference to a list and will try to delete all odd members. I am having a sligh

4条回答
  •  情话喂你
    2021-01-16 09:10

    Ok, I found one way to do this, and that was to move p++ from for loop declaration into inside it, like this.

    void removeOdds(list& myvector)
    {
        for(list::iterator p=myvector.begin(); p !=myvector.end();)
        {
            if(*p%2 !=0)
            {
                list::iterator temp=myvector.erase(p);
                p=temp;
            }
            else
                p++;
        }
    } 
    

    Now I am curious if I can do this and still keep my for loop intact.

提交回复
热议问题