Modern way to filter STL container?

前端 未结 6 954
不知归路
不知归路 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 15:44

    Improved pjm code following underscore-d suggestions:

    template 
    Cont filter(const Cont &container, Pred predicate) {
        Cont result;
        std::copy_if(container.begin(), container.end(), std::back_inserter(result), predicate);
        return result;
    }
    

    Usage:

    std::vector myVec = {1,4,7,8,9,0};
    
    auto filteredVec = filter(myVec, [](int a) { return a > 5; });
    

提交回复
热议问题