fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <functional>
  5. #include <algorithm>
  6.  
  7. template<typename T, typename U>
  8. void apply(T collBegin, T collEnd, std::function<bool(U const &)> f1, std::function<U(U const &)> f2, std::function<U(U const &)> f3)
  9. {
  10. std::for_each(collBegin, collEnd, [&](auto &el) { el = f1(el) ? f2(el) : f3(el); });
  11. }
  12.  
  13. int main()
  14. {
  15. std::function<bool(int const &)> predicate = [](int const &arg) -> bool { return arg % 2 == 0; };
  16. std::function<int(int const &)> passed = [](int const &arg) -> int { return arg / 2; };
  17. std::function<int(int const &)> rejected = [](int const &arg) -> int { return (3 * arg) + 1; };
  18.  
  19. int arr[]{ 1,2,3,4,5,6,7,8,9 };
  20. apply(arr, arr + sizeof(arr)/sizeof(int), predicate, passed, rejected);
  21.  
  22. std::vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
  23. apply(vec.begin(), vec.end(), predicate, passed, rejected);
  24.  
  25. std::list<int> lis(vec.begin(), vec.end());
  26. apply(lis.begin(), lis.end(), predicate, passed, rejected);
  27.  
  28. for (auto e : lis) std::cout << e << " ";
  29. std::cout << '\n';
  30. }
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
1 2 16 4 4 5 34 1 7