C++ Custom Comparison Function with Template as Function Parameter -
i'm trying implement/use comparator style interface 1 find in java allow me pass generic comparator type function , use sort data set.
this because need variety of different comparison functions , want able pass 1 need sort function.
here's code snippet of have far , can tell mean:
void population::sort(const std::shared_ptr<comparator<solution>>& comparator) { std::sort(data.begin(), data.end(), comparator.get()); }
and comparator interface i've tried implement
template <typename t> class comparator : public std::binary_function<t,t,bool> { public: virtual ~comparator (); virtual bool operator() ( const t &o1, const t &o2 ) = 0; };
it's obvious i'm doing wrong don't know whole lot of c++.
cheers!
unless explicitly need change comparison predicate @ run-time opt make population::sort function template function:
struct person { std::vector<int> v; template<typename p> void sort(p& p) { std::sort(v.begin(), v.end(), p); } };
this gives wide range of options predicate. such as:
bool mycompare(int a, int b) { return < b; } struct predicate { bool operator()(int a, int b) { return < b; } }; struct myclass { bool function(int a, int b) { return < b; } }; int main() { person p; // can use lambda p.sort([](int a, int b){return < b;}); // can use functor predicate pred; p.sort(pred); // can use free function p.sort(mycompare); // can bind class member function myclass c; p.sort(std::bind(&myclass::function, &c, std::placeholders::_1, std::placeholders::_2)); std::copy(p.v.begin(), p.v.end(), std::ostream_iterator<int>(std::cout)); }
using template functions allows lot of flexibility.
Comments
Post a Comment