Modern way to filter STL container?

前端 未结 6 949
不知归路
不知归路 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:49

    In C++20, use filter view from the ranges library: (requires #include )

    // namespace views = std::ranges::views;
    vec | views::filter([](int a){ return a % 2 == 0; })
    

    lazily returns the even elements in vec.

    (See [range.adaptor.object]/4 and [range.filter])


    This is already supported by GCC 10 (live demo). For Clang and older versions of GCC, the original range-v3 library can be used too, with #include (or #include ) and the ranges::views namespace instead of std::ranges::views (live demo).

提交回复
热议问题