fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. //4. Implement count_if() yourself. Test it.
  7.  
  8. template<typename Iter, typename Predicate>
  9. typename iterator_traits<Iter>::value_type
  10. count_if(Iter first, Iter last, Predicate pred)
  11. {
  12. typename iterator_traits<Iter>::value_type sum = 0;
  13. for (Iter it = first; it != last; it++)
  14. {
  15. if (pred(*it)) // trouble here?
  16. {
  17. sum++;
  18. }
  19. }
  20. return sum;
  21. }
  22.  
  23. int main()
  24. {
  25. vector<int> v {1, 2, 3, 1, 5, -1};
  26. cout << count_if(v.begin(), v.end(), [](int n) { return n > 1; }) << endl;
  27. return 0;
  28. }
  29.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
3