Advertisement
avr39-ripe

copy_ifExample

Apr 2nd, 2020
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template <typename T>
  4. void forEach(T* arrB, T* arrE, void(*action)(T& el))
  5. {
  6.     while (arrB != arrE)
  7.     {
  8.         if (action) { action(*arrB++); };
  9.     }
  10. }
  11.  
  12. void printElement(int& el)
  13. {
  14.     std::cout << el << ' ';
  15. };
  16.  
  17. template <typename T>
  18. int copy_if(T* srcB, T* srcE, T* destB, T* destE, bool(*pred)(T& elem))
  19. {
  20.     int copyCount{ 0 };
  21.     while (destB != destE and srcB != srcE)
  22.     {
  23.         if (pred(*srcB))
  24.         {
  25.             *destB++ = *srcB;
  26.             ++copyCount;
  27.         }
  28.         ++srcB;
  29.     }
  30.     return copyCount;
  31. }
  32.  
  33. bool trueer(int& el)
  34. {
  35.     return true;
  36. }
  37.  
  38. bool falseer(int& el)
  39. {
  40.     return false;
  41. }
  42.  
  43. bool evener(int& el)
  44. {
  45.     return !(el % 2);
  46. }
  47.  
  48. bool odder(int& el)
  49. {
  50.     return (el % 2);
  51. }
  52.  
  53. bool greater5(int& el)
  54. {
  55.     return el > 5;
  56. }
  57.  
  58. int main()
  59. {
  60.     const int size{ 10 };
  61.     int arr[size]{ 1,2,3,4,5,6,7,8,9,10 };
  62.     int* arrBegin{ arr };
  63.     int* arrEnd{ arr + size };
  64.  
  65.     const int size1{ 3 };
  66.     int arr1[size1]{};
  67.     int* arr1Begin{ arr1 };
  68.     int* arr1End{ arr1 + size1 };
  69.  
  70.     int copyCount{ 0 };
  71.  
  72.     forEach(arrBegin, arrEnd, printElement);
  73.     std::cout << '\n';
  74.     forEach(arr1Begin, arr1End, printElement);
  75.     std::cout << '\n';
  76.     copyCount = copy_if(arrBegin, arrEnd, arr1Begin, arr1End, greater5);
  77.     forEach(arr1Begin, arr1End, printElement);
  78.     std::cout << '\n' << copyCount << " elements copied\n";
  79.     std::cout << '\n';
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement