count.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /// \file
  2. // Range v3 library
  3. //
  4. // Copyright Eric Niebler 2014-present
  5. //
  6. // Use, modification and distribution is subject to the
  7. // Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at
  9. // http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. // Project home: https://github.com/ericniebler/range-v3
  12. //
  13. #ifndef RANGES_V3_ALGORITHM_COUNT_HPP
  14. #define RANGES_V3_ALGORITHM_COUNT_HPP
  15. #include <utility>
  16. #include <range/v3/range_fwd.hpp>
  17. #include <range/v3/functional/identity.hpp>
  18. #include <range/v3/functional/invoke.hpp>
  19. #include <range/v3/iterator/concepts.hpp>
  20. #include <range/v3/iterator/traits.hpp>
  21. #include <range/v3/range/access.hpp>
  22. #include <range/v3/range/concepts.hpp>
  23. #include <range/v3/range/traits.hpp>
  24. #include <range/v3/utility/static_const.hpp>
  25. #include <range/v3/detail/prologue.hpp>
  26. namespace ranges
  27. {
  28. /// \addtogroup group-algorithms
  29. /// @{
  30. RANGES_FUNC_BEGIN(count)
  31. /// \brief function template \c count
  32. template(typename I, typename S, typename V, typename P = identity)(
  33. requires input_iterator<I> AND sentinel_for<S, I> AND
  34. indirect_relation<equal_to, projected<I, P>, V const *>)
  35. constexpr iter_difference_t<I> //
  36. RANGES_FUNC(count)(I first, S last, V const & val, P proj = P{})
  37. {
  38. iter_difference_t<I> n = 0;
  39. for(; first != last; ++first)
  40. if(invoke(proj, *first) == val)
  41. ++n;
  42. return n;
  43. }
  44. /// \overload
  45. template(typename Rng, typename V, typename P = identity)(
  46. requires input_range<Rng> AND
  47. indirect_relation<equal_to, projected<iterator_t<Rng>, P>, V const *>)
  48. constexpr iter_difference_t<iterator_t<Rng>> //
  49. RANGES_FUNC(count)(Rng && rng, V const & val, P proj = P{})
  50. {
  51. return (*this)(begin(rng), end(rng), val, std::move(proj));
  52. }
  53. RANGES_FUNC_END(count)
  54. namespace cpp20
  55. {
  56. using ranges::count;
  57. }
  58. /// @}
  59. } // namespace ranges
  60. #include <range/v3/detail/epilogue.hpp>
  61. #endif