Created
November 9, 2010 16:03
-
-
Save peteb/669284 to your computer and use it in GitHub Desktop.
Implements a simple filter function in C++
This file contains 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> | |
#include <iostream> | |
#include <functional> | |
#include <iterator> | |
template <class Functor> | |
class Not | |
{ | |
public: | |
Not(Functor & f) : func(f) {} | |
template <typename ArgType> | |
bool operator()(ArgType & arg) {return !func(arg);} | |
private: | |
Functor & func; | |
}; | |
template<typename T, typename B> | |
T filter(T list, B pred) { | |
T ret; | |
std::remove_copy_if( | |
list.begin(), | |
list.end(), | |
std::back_insert_iterator<T>(ret), | |
Not<B>(pred) | |
); | |
return ret; | |
} | |
/* | |
bool keep(int value) { | |
return value < 2; | |
} | |
int main() { | |
std::vector<int> hej; | |
hej.push_back(1); | |
hej.push_back(3); | |
hej.push_back(8); | |
std::vector<int> result = filter(hej, keep); | |
std::cout << "filtered values: " << std::endl; | |
std::copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, ", ")); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment