Skip to content

Instantly share code, notes, and snippets.

@melvyniandrag
Last active January 15, 2018 17:25
Show Gist options
  • Save melvyniandrag/493206d0ae351978cb84b0c6c5deb019 to your computer and use it in GitHub Desktop.
Save melvyniandrag/493206d0ae351978cb84b0c6c5deb019 to your computer and use it in GitHub Desktop.
lambda functions
#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;
}
}
#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