Last active
January 15, 2018 17:25
-
-
Save melvyniandrag/493206d0ae351978cb84b0c6c5deb019 to your computer and use it in GitHub Desktop.
lambda functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "template.h" | |
#include <vector> | |
#include <iostream> | |
int main(){ | |
std::vector<int> V{1, 2, 3, 4, 5}; | |
std::vector<int> filtered = filter( [](int i){return i %2 == 0;}, V); | |
for( auto f : filtered ){ | |
std::cout << f << std::endl; | |
} | |
int j = 4; | |
// The ampersand makes local variables visible inside the lambda. | |
std::vector<int> filtered2 = filter( [&](int i){return i > j;}, V); | |
for( auto f : filtered2 ){ | |
std::cout << f << std::endl; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
template<typename func, typename T> | |
std::vector<T> filter( func f, std::vector<T> arr) | |
{ | |
std::vector<T> ret; | |
for (auto i : arr ){ | |
if ( f(i) ){ | |
ret.push_back( i ); | |
} | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment