简体   繁体   English

中的make_heap()函数算法<algorithm>

[英]algorithm of make_heap() function in <algorithm>

I was just experimenting with make_heap() function in C++. 我只是在使用C ++中的make_heap()函数进行实验。 Following is the code where I am keeping a track of the elements that are being compared every time the bool predicate() is called, by printing them. 以下是我每次打印bool predicate()时都要比较的元素的代码,通过打印它们来跟踪它们。

#include <iostream>
#include <algorithm>
using namespace std;

// bool predicate function to make a min heap
bool predicate(int a, int b){
    cout << a << "  " << b << endl;
    if(a >= b){ return 1; }
    return 0;
}


int main(){
    int arr[] = {3,2,1,-1,-2};
    make_heap(arr, arr+5, predicate);
    return 0;
}

The output that I am getting is : 我得到的输出是:
-2 -1 -2 -1
-2 2 -2 2
1 -2 1 -2
2 -1 2 -1
-1 3 -1 3

But I was expecting the following output, keeping in view the standard algorithm : 但是我期待以下输出,同时注意标准算法:
-2 -1 -2 -1
-2 2 -2 2
1 -2 1 -2
3 -2 3 -2
2 -1 2 -1
-1 3 -1 3

any help ? 有什么帮助吗?

I would not say there is an algorithm standardized enough so that you expect specific set of comparisons to be performed. 我不会说有一种足够标准化的算法,因此您希望执行一组特定的比较。 What is standardized is the complexity of the algorithm and as long as the number of comparisons is of linear order you should be good to go. 什么标准化是算法的复杂度,并且只要比较的数量是线性顺序的,你应该是好去。 Moreover it seems stl performs better than you in term of number of comparisons so you should not be worried. 而且,在比较次数方面, stl似乎比您更好。因此,您不必担心。

As suggested in the comments you can always read the code of the implementation of std::make_heap that your compiler uses but there is no guarantee the same implementation will be used in all implementations of stl . 如注释中所建议,您始终可以阅读编译器使用的std::make_heap实现的代码,但不能保证在stl所有实现中都将使用相同的实现。

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

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