List Iterator Remove()

后端 未结 4 593
天涯浪人
天涯浪人 2020-12-08 06:19

I have a list iterator that goes through a list and removes all the even numbers. I can use the list iterator to print out the numbers fine but I cannot use the list\'s remo

4条回答
  •  离开以前
    2020-12-08 06:21

    There are a few issues with your code above. Firstly, the remove will invalidate any iterators that are pointing at the removed elements. You then go on to continue using the iterator. It is difficult to tell which element(s) remove would erase in the general case (although not in yours) since it can remove more than one.

    Secondly, you are probably using the wrong method. Remove will iterate through all of the items in the list looking for any matching elements - this will be inefficient in your case because there is only one. It looks like you should use the erase method, you probably only want to erase the item at the position of the iterator. The good thing about erase is it returns an iterator which is at the next valid position. The idiomatic way to use it is something like this:

    //remove even numbers
    for(itr = listA.begin(); itr != listA.end();)
    {
        if ( *itr % 2 == 0 )
        {
            cout << *itr << endl;
            itr=listA.erase(itr);
        }
        else
          ++itr;
    }
    

    Finally, you could also use remove_if to do the same as you are doing:

    bool even(int i) { return i % 2 == 0; }
    
    listA.remove_if(even);
    

提交回复
热议问题