Advertisement
Guest User

Functional map/filter C++

a guest
Jan 12th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <type_traits>
  5.  
  6. using namespace std;
  7.  
  8. /*
  9. Terminology - callback : A function passed as a parameter to another function
  10. */
  11.  
  12.  
  13. //Returns an array based off the input array manipulated by the callback
  14. template <class Container, class Funktion>
  15. auto _map (const Container &cont, Funktion fun) {
  16.     std::vector<typename std::result_of<Funktion(const typename Container::value_type&)>::type> ret;
  17.     for (const auto &v : cont) {
  18.         ret.push_back(fun(v));
  19.     }
  20.     return ret;
  21. }
  22.  
  23. //Filters higher function, utilizes C++' remove_if function
  24. template <typename Collection,typename Predicate>
  25. Collection filterNot(Collection col,Predicate predicate ) {
  26.     auto returnIterator = std::remove_if(col.begin(),col.end(),predicate);
  27.     col.erase(returnIterator,std::end(col));
  28.     return col;
  29. }
  30.  
  31. //Uses filterNot with a NOT operator and returns an array of which the elements from the input array are passed to the callback and return true.
  32. template <typename Collection,typename Predicate>
  33. Collection filter(Collection col,Predicate predicate) {
  34.  //capture the predicate in order to be used inside function
  35.  auto fnCol = filterNot(col,[predicate](typename Collection::value_type i) { return !predicate(i);});
  36.  return fnCol;
  37. }
  38.  
  39. //Prints anything passed to it
  40. template <class T>
  41. void printEverything( std::vector<T> vec )
  42. {
  43.     for( typename std::vector<T>::iterator iter = vec.begin();  iter != vec.end(); ++iter )
  44.     {
  45.         std::cout << *iter << std::endl ;
  46.     }
  47. }
  48.  
  49. int square(int a){
  50.     return a * a;
  51. }
  52.  
  53. //If the remainder of x / 2 is 0, the number is even therefore returns true
  54. bool isEven(int x){
  55.     return x % 2 == 0;
  56. }
  57.  
  58. int main()
  59. {
  60.     /*
  61.     // playing with lambda expressions
  62.     auto func = [] () { std::cout << "Hello World\n"; };
  63.     func();
  64.     int result = [](int input) -> int {return 2 * input; }(10);
  65.     std::cout << result << std::endl;
  66.     int otherResult = [](int a,int b) -> int { return a + b; }(2,4);
  67.     */
  68.  
  69.     std::vector<int> input({4,6,7,8,9});
  70.     auto squaredNumbersArray =_map(input, square);
  71.     auto evenNumbersArray = filter(input, isEven);
  72.     printEverything(squaredNumbersArray);
  73.     printEverything(evenNumbersArray);
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement