xref: /llvm-project/libcxx/include/__algorithm/ranges_count_if.h (revision 1306b1025c507ec8c406a975558007e3e94e5cbd)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef _LIBCPP___ALGORITHM_RANGES_COUNT_IF_H
10 #define _LIBCPP___ALGORITHM_RANGES_COUNT_IF_H
11 
12 #include <__config>
13 #include <__functional/identity.h>
14 #include <__functional/invoke.h>
15 #include <__functional/ranges_operations.h>
16 #include <__iterator/concepts.h>
17 #include <__iterator/incrementable_traits.h>
18 #include <__iterator/projected.h>
19 #include <__ranges/access.h>
20 #include <__ranges/concepts.h>
21 #include <__utility/move.h>
22 
23 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
24 #  pragma GCC system_header
25 #endif
26 
27 #if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
28 
29 _LIBCPP_BEGIN_NAMESPACE_STD
30 
31 namespace ranges {
32 template <class _Iter, class _Sent, class _Proj, class _Pred>
33 _LIBCPP_HIDE_FROM_ABI constexpr
34 iter_difference_t<_Iter> __count_if_impl(_Iter __first, _Sent __last,
35                                              _Pred& __pred, _Proj& __proj) {
36   iter_difference_t<_Iter> __counter(0);
37   for (; __first != __last; ++__first) {
38     if (std::invoke(__pred, std::invoke(__proj, *__first)))
39       ++__counter;
40   }
41   return __counter;
42 }
43 
44 namespace __count_if {
45 struct __fn {
46   template <input_iterator _Iter, sentinel_for<_Iter> _Sent, class _Proj = identity,
47             indirect_unary_predicate<projected<_Iter, _Proj>> _Predicate>
48   _LIBCPP_HIDE_FROM_ABI constexpr
49   iter_difference_t<_Iter> operator()(_Iter __first, _Sent __last, _Predicate __pred, _Proj __proj = {}) const {
50     return ranges::__count_if_impl(std::move(__first), std::move(__last), __pred, __proj);
51   }
52 
53   template <input_range _Range, class _Proj = identity,
54             indirect_unary_predicate<projected<iterator_t<_Range>, _Proj>> _Predicate>
55   _LIBCPP_HIDE_FROM_ABI constexpr
56   range_difference_t<_Range> operator()(_Range&& __r, _Predicate __pred, _Proj __proj = {}) const {
57     return ranges::__count_if_impl(ranges::begin(__r), ranges::end(__r), __pred, __proj);
58   }
59 };
60 } // namespace __count_if
61 
62 inline namespace __cpo {
63   inline constexpr auto count_if = __count_if::__fn{};
64 } // namespace __cpo
65 } // namespace ranges
66 
67 _LIBCPP_END_NAMESPACE_STD
68 
69 #endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
70 
71 #endif // _LIBCPP___ALGORITHM_RANGES_COUNT_IF_H
72