Modern way to filter STL container?

前端 未结 6 959
不知归路
不知归路 2020-12-07 15:20

Coming back to C++ after years of C# I was wondering what the modern - read: C++11 - way of filtering an array would be, i.e. how can we achieve something similar to this Li

6条回答
  •  余生分开走
    2020-12-07 16:07

    See the example from cplusplus.com for std::copy_if:

    std::vector foo = {25,15,5,-5,-15};
    std::vector bar;
    
    // copy only positive numbers:
    std::copy_if (foo.begin(), foo.end(), std::back_inserter(bar), [](int i){return i>=0;} );
    

    std::copy_if evaluates the lambda expression for every element in foo here and if it returns true it copies the value to bar.

    The std::back_inserter allows us to actually insert new elements at the end of bar (using push_back()) with an iterator without having to resize it to the required size first.

提交回复
热议问题