count_if.h 719 B

123456789101112131415161718192021222324252627282930
  1. //
  2. // count_if.h
  3. // stream
  4. //
  5. // Created by Sam Jaffe on 4/2/23.
  6. //
  7. #pragma once
  8. #include <stream/forward.h>
  9. #include <stream/detail/identity.h>
  10. #include <stream/detail/invoke.h>
  11. namespace stream::ranges {
  12. template <typename It, typename S, typename Pred,
  13. typename Proj = detail::identity>
  14. auto count_if(It it, S end, Pred pred, Proj proj = {}) {
  15. size_t result = 0;
  16. for (; it != end; ++it) {
  17. if (detail::invoke(pred, *it, proj)) { ++result; }
  18. }
  19. return result;
  20. }
  21. template <typename Stream, typename Pred, typename Proj = detail::identity>
  22. auto count_if(Stream const & stream, Pred pred, Proj proj = {}) {
  23. return count_if(stream.begin(), stream.end(), std::ref(pred), std::ref(proj));
  24. }
  25. }