At first . I suggest that if you want to compare collections regardless of their ordering, you can search for std::set with set_difference , set_intersection , set_union and set_symmetric_difference
To your question
You are trying to implement sort-by-policy; if you canโt just specialize std::less<> (which exists for this specific purpose), you can knock down the user policy yourself: ( code that runs on code code. Org )
#include <list> #include <vector> #include <iostream> #include <iterator> #include <algorithm> namespace applogic { template <typename T> struct sort_policy { typedef std::less<T> predicate_t; }; template <> struct sort_policy<std::string> { struct _Cmp { bool operator()(const std::string& a, const std::string& b) { return a.length()>b.length(); } }; typedef _Cmp predicate_t; }; template <typename C> void sort(C& cont) { typedef typename sort_policy<typename C::value_type>::predicate_t P; std::sort(cont.begin(), cont.end(), P()); } template <typename T> void sort(std::list<T>& cont) { typedef typename sort_policy<T>::predicate_t P; cont.sort(P()); } } template <class C> static void dump(const C& cont, const std::string& msg="") { std::cout << msg; std::copy(cont.begin(), cont.end(), std::ostream_iterator<typename C::value_type>(std::cout, ", ")); std::cout << std::endl; } int main() { using applogic::sort; std::vector<int> ints; ints.push_back(13); ints.push_back(-3); ints.push_back(7); dump(ints, "before: "); sort(ints); dump(ints, "after: "); std::list<std::string> strings; strings.push_back("very very long"); strings.push_back("tiny"); strings.push_back("medium size"); dump(strings, "before: "); sort(strings); dump(strings, "after: "); return 0; }
source share