所以我偶然发现了这个密码。我只添加了谓词参数。
template<class RandomAccessIt, class Predicate = std::less<>> inline
void heap_sort(RandomAccessIt first, RandomAccessIt last, Predicate predicate = Predicate())
{
std::make_heap(first, last);
std::sort_heap(first, last, predicate);
}现在,正如标题所述,它可以很好地处理:
int arr[] = { 143, 2, 365, 4, 5 };
heap_sort(std::begin(arr), std::end(arr));但是给出了一个调试错误(无效堆),其中:
int arr[] = { 143, 2, 365, 4, 5 };
heap_sort(std::begin(arr), std::end(arr), std::greater<>());我也和其他容器一起试过这个。那么允许定制UnaryPredicate有什么意义呢?
发布于 2015-12-05 14:12:26
std::make_heap需要用相同的谓词调用:
std::make_heap(first, last, predicate);
std::sort_heap(first, last, predicate);否则,堆是使用错误的标准构建的,并且不会是相对于predicate的最大堆。这违反了std::sort_heap(first, last, predicate);的先决条件。
https://stackoverflow.com/questions/34106440
复制相似问题