Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <type_traits>
- using namespace std;
- /*
- Terminology - callback : A function passed as a parameter to another function
- */
- //Returns an array based off the input array manipulated by the callback
- template <class Container, class Funktion>
- auto _map (const Container &cont, Funktion fun) {
- std::vector<typename std::result_of<Funktion(const typename Container::value_type&)>::type> ret;
- for (const auto &v : cont) {
- ret.push_back(fun(v));
- }
- return ret;
- }
- //Filters higher function, utilizes C++' remove_if function
- template <typename Collection,typename Predicate>
- Collection filterNot(Collection col,Predicate predicate ) {
- auto returnIterator = std::remove_if(col.begin(),col.end(),predicate);
- col.erase(returnIterator,std::end(col));
- return col;
- }
- //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.
- template <typename Collection,typename Predicate>
- Collection filter(Collection col,Predicate predicate) {
- //capture the predicate in order to be used inside function
- auto fnCol = filterNot(col,[predicate](typename Collection::value_type i) { return !predicate(i);});
- return fnCol;
- }
- //Prints anything passed to it
- template <class T>
- void printEverything( std::vector<T> vec )
- {
- for( typename std::vector<T>::iterator iter = vec.begin(); iter != vec.end(); ++iter )
- {
- std::cout << *iter << std::endl ;
- }
- }
- int square(int a){
- return a * a;
- }
- //If the remainder of x / 2 is 0, the number is even therefore returns true
- bool isEven(int x){
- return x % 2 == 0;
- }
- int main()
- {
- /*
- // playing with lambda expressions
- auto func = [] () { std::cout << "Hello World\n"; };
- func();
- int result = [](int input) -> int {return 2 * input; }(10);
- std::cout << result << std::endl;
- int otherResult = [](int a,int b) -> int { return a + b; }(2,4);
- */
- std::vector<int> input({4,6,7,8,9});
- auto squaredNumbersArray =_map(input, square);
- auto evenNumbersArray = filter(input, isEven);
- printEverything(squaredNumbersArray);
- printEverything(evenNumbersArray);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement