fork(1) download
  1. #include <vector>
  2. #include <string>
  3. #include <iostream>
  4. #include <list>
  5. using namespace std;
  6.  
  7. template<class InputIt1, class InputIt2, class BinaryFunction>
  8. BinaryFunction for_each_impl(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryFunction f, std::random_access_iterator_tag, std::random_access_iterator_tag)
  9. {
  10. std::cout << "Optimized for random access.\n";
  11. if (last1 - first1 < last2 - first2)
  12. {
  13. for (; first1 != last1; ++first1, ++first2) {
  14. f(*first1, *first2);
  15. }
  16. }
  17. else
  18. {
  19. for (; first2 != last2; ++first1, ++first2) {
  20. f(*first1, *first2);
  21. }
  22. }
  23.  
  24. return f;
  25. }
  26.  
  27. template<class InputIt1, class InputIt2, class BinaryFunction>
  28. BinaryFunction for_each_impl(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryFunction f, std::input_iterator_tag, std::input_iterator_tag)
  29. {
  30. std::cout << "Generic implementation.\n";
  31. for (; first1 != last1 && first2 != last2; ++first1, ++first2) {
  32. f(*first1, *first2);
  33. }
  34. return f;
  35. }
  36.  
  37. template<class InputIt1, class InputIt2, class BinaryFunction>
  38. BinaryFunction for_each(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryFunction f)
  39. {
  40. typedef typename std::iterator_traits<InputIt1>::iterator_category Category1;
  41. typedef typename std::iterator_traits<InputIt2>::iterator_category Category2;
  42. return for_each_impl(first1, last1, first2, last2, f, Category1(), Category2());
  43. }
  44.  
  45. template <template <typename, typename> class ContainerT>
  46. void test()
  47. {
  48. ContainerT<int, std::allocator<int>> example;
  49. example.push_back(42);
  50. example.push_back(1729);
  51. ContainerT<string, std::allocator<string>> example2;
  52. example2.push_back("forty two");
  53. example2.push_back("seventeen twenty nine");
  54. for_each(example.cbegin(), example.cend(), example2.cbegin(), example2.cend(),
  55. [](int left, string const& right) { std::cout << left << " is " << right << "\n"; });
  56. }
  57.  
  58. int main() {
  59. test<list>();
  60. test<vector>();
  61. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Generic implementation.
42 is forty two
1729 is seventeen twenty nine
Optimized for random access.
42 is forty two
1729 is seventeen twenty nine