简体   繁体   English

std :: sort_heap降序

[英]std::sort_heap in descending order

So I came across this code. 所以我遇到了这段代码。 The only thing I added was the predicate parameter. 我添加的唯一内容是谓词参数。

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);
}

Now as the title says, it works fine with: 现在,正如标题所述,它可以与以下命令配合使用:

int arr[] = { 143, 2, 365, 4, 5 };
heap_sort(std::begin(arr), std::end(arr));

But gives me a debug error (invalid heap) with: 但是给我一个调试错误(无效的堆):

int arr[] = { 143, 2, 365, 4, 5 };
heap_sort(std::begin(arr), std::end(arr), std::greater<>());

I also tried this with other containers. 我也尝试了其他容器。 What is the point of allowing a custom UnaryPredicate then? 那么允许自定义UnaryPredicate有什么意义呢?

std::make_heap

needs to be called with the same predicate: 需要使用相同的谓词来调用:

std::make_heap(first, last, predicate);
std::sort_heap(first, last, predicate);

Otherwise, the heap is built with the wrong criterion and will not be a max heap with respect to predicate . 否则,将使用错误的标准构建堆,并且就predicate而言,堆将不是最大堆。 This violates the precondition for std::sort_heap(first, last, predicate); 这违反了std::sort_heap(first, last, predicate);的前提std::sort_heap(first, last, predicate); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM