Suppose I want to get std::sort to sort a vector of pointers to int's, based on the value of the int's the pointers point to. Ignore the obvious performance issue there. Simple huh? Make a function:
bool sort_helper(const int *a, const int *b) { return *a < *b; } and supply to the std::sort.
Now, if we also want to do the same thing with a vector of pointers to large objects. The same thing applies: first we define a < operator in the object, then make a function along the following lines:
bool sort_helper(const ob_type *a, const ob_type *b) { return *a < *b; } or whatever, supply that to std::sort.
Now, and this is where it gets tricky: what if we want to sort a vector of pointers to any type, with any arbitrary compare function (we make the assumption that whatever type we use that function with, will be able to work with it)- supplying a template version of the sort_helper function above is easy:
template <class ob_type> bool sort_helper(const ob_type *a, const ob_type *b) { return *a < *b; } However, supplying an arbitrary compare function is harder: Something like this-
template <typename comparison_function, class ob_type> bool sort_template_helper(const ob_type *a, const ob_type *b) { return comparison_function(*a, *b); } template <typename comparison_function, class iterator_type> void t_sort(const iterator_type &begin, const iterator_type &end, comparison_function compare) { std::sort(begin, end, sort_template_helper<compare>); } is what I'd like to do, but doing this:
bool less_than(const int a, const int b) { return a < b; } void do_stuff() { t_sort(ipoint_vector.begin(), ipoint_vector.end(), sort_template_helper<less_than>); } Doesn't work. How can I sort a vector of pointers to a known type, by the value of the objects pointed to, using an arbitrary comparison function, supplied to std::sort? Assume that the test case I am presenting here is an insanely simplified version of the actual scenario, and that there are valid reasons for wanting to do things this way, that would take too long to go into and distract from the problem.
[EDIT: for various reasons, am looking for a solution that also works in C++03 - Thanks to Nir for his C++14 answer tho']