STL list, delete all the odd numbers

前端 未结 4 1363
不知归路
不知归路 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:01

    Since you're learning, you better forget the 'C' way of doing things and jump directly into C++11.

    Here's your code in modern C++

    void removeOdds(vector& myvector)
    {
        auto new_end = std::remove_if (myvector.begin(), myvector.end(), 
         [](const auto& value){ return value%2 !=0 }
        );    
        myvector.erase(new_end, myvector.end());
    }
    

    As far as your code goes, you can improve readability a lot just by using auto Please not that it is risky to remove elements while looping on a container. You're usually fine with a vector, but when you start using other data structures things get more nasty.

提交回复
热议问题