STL list, delete all the odd numbers

前端 未结 4 1366
不知归路
不知归路 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 08:55

    Method erase returns iterator to the next element after deleted. So the usual approach to such a task is the following

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

    As for your code then the loop statement always increases the iterator

    for(list::iterator p=myvector.begin(); p !=myvector.end();p++)
                                                                   ^^^^  
    

    Take into account that class std::list has methods remove and remove_if that erase all elements that satisfy the given criteria.

    Here is a demonstrative program that shows the both approaches

    #include 
    #include 
    
    void removeOdds( std::list &myvector )
    {
        for ( auto it = myvector.begin(); it != myvector.end();  )
        {
            if ( *it % 2 !=0 )
            {
                it = myvector.erase( it );
            }
            else
            {
                ++it;
            }
        }
    }
    
    int main()
    {
        std::list l = { 1, 3, 5, 2, 6, 7 };
    
        for ( auto x : l ) std::cout << x << ' ';
        std::cout << std::endl;
    
        removeOdds( l );
    
        for ( auto x : l ) std::cout << x << ' ';
        std::cout << std::endl;
    
        l = { 1, 3, 5, 2, 6, 7 };
    
        for ( auto x : l ) std::cout << x << ' ';
        std::cout << std::endl;
    
        l.remove_if( []( int x ) { return x % 2; } );
    
        for ( auto x : l ) std::cout << x << ' ';
        std::cout << std::endl;
    }
    

    The program output is

    1 3 5 2 6 7 
    2 6 
    1 3 5 2 6 7 
    2 6 
    

提交回复
热议问题