The C ++ Standard Library suggests passing Comparator to std::sort. However, I have many cases in my code where I want to sort a list of objects Tusing a function f. Such a comparative example would be valid:
bool compare(const T& a, const T& b) {
return f(a) < f(b);
}
This is not optimal. fevaluates slowly but returns the same value for each call with the same object T. So what I would prefer to do is calculate fonce for each object in the range, and then use these results to sort them.
My goal is to write this function (which I could not do):
template <typename IterT, typename Transformation>
void sort(IterT left, IterT right, Transformation f) { }
So after this call f(*iter) <= f(*std::next(iter))for everyone iterin the sequence leftbefore right.
In addition, the function must satisfy the following requirements:
- Does not allocate any additional type objects
T. - Repeatedly evaluates
fsmoothly std::distance(left, right). - Maintains the overall complexity of O (n log n).
- Must be implemented in terms of std :: sort. Of course, I could solve this problem by implementing my own type of merge, but I would like to avoid this.
(preferably C ++ 11, C ++ 14 is also good)
source
share