Skip to content

Instantly share code, notes, and snippets.

@sideb0ard
Created November 1, 2017 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sideb0ard/464875efbcd25c86cd36e16d50a6ab3a to your computer and use it in GitHub Desktop.
Save sideb0ard/464875efbcd25c86cd36e16d50a6ab3a to your computer and use it in GitHub Desktop.
functional template
#include <iostream>
#include <vector>
#include <list>
typedef std::vector<int> Ints;
using std::vector;
bool is_even(int x)
{
return x % 2 == 0;
}
template<typename F, typename T>
T keep_if(F f, const T& xs)
{
T ys;
for (auto x : xs)
if (f(x))
ys.push_back(x);
return ys;
}
int main()
{
Ints xs = {0, 1, 2, 3, 4, 5};
const auto ys = keep_if(is_even, xs);
std::cout << "Results:";
for (auto y : ys)
std::cout << y << " ";
std::cout << std::endl;
std::list<int> xxs = { 5, 6, 7, 8, 9, 10};
const auto yys = keep_if(is_even, xxs);
std::cout << "Resultss2:";
for (auto y : yys)
std::cout << y << " ";
std::cout << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment