STL list, delete all the odd numbers

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

    The easiest way to do it would be to use std::list::remove_if. This removes elements from the list based on a unary predicate. For example,

    myvector.remove_if([](int n) { return n % 2 != 0; });
    

    The best way to work with the "STL"* is to know what is in it.

    For pre-C++11 implementations (such as the actual STL), you can pass a function:

    bool is_odd(int n) { return n % 2 != 0; }
    
    myvector.remove_if(is_odd);
    

    *"STL" means the STL but this also applies the C++ standard library

提交回复
热议问题