I am currently writing my own merge sort implementation for practice. When combining the left and right parts of the list, it makes sense to create a temporary list only from the smaller side. However, the logic changes depending on which copy was copied to a temporary one.
My function has the following signature:
template<class RandomIt, class Compare> void Merge(RandomIt begin, RandomIt middle, RandomIt end, Compare Comp);
I had a smart idea to check the lengths of [begin,middle) and [middle,end) at the beginning, and if there was more left, convert iterators to inverse iterators and call the function recursively. Like this:
template<class RandomIt, class Compare> void Merge(RandomIt begin, RandomIt middle, RandomIt end, Compare Comp) { size_t leftLength = std::distance(begin, middle); size_t rightLength = std::distance(middle, end); if (leftLength > rightLength) { using ReverseIterator = std::reverse_iterator<RandomIt>; Merge(ReverseIterator(end), ReverseIterator(std::next(middle)), ReverseIterator(begin), Comp); return; }
However, the compiler gives a rather thick error.
fatal error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum)
I created a small standalone application on ideone.com that reproduces the error.
EDIT: for mergesort, I just realized that this does not work, because the Compare function has to be canceled.