【问题标题】:algorithm of make_heap() function in <algorithm><algorithm> 中 make_heap() 函数的算法
【发布时间】:2013-11-28 15:16:25
【问题描述】:

我只是在 C++ 中试验 make_heap() 函数。以下是我在每次调用 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;
}

我得到的输出是:
-2 -1
-2 2
1 -2
2 -1
-1 3

但我期待以下输出,同时考虑标准算法:
-2 -1
-2 2
1 -2
3 -2
2 -1
-1 3

有什么帮助吗?

【问题讨论】:

  • 您拥有 您的 实现的make_heap 的模板源。有什么东西阻止你通过它吗?
  • C++ 实现的make_heap 通过最少的比较创建了堆,你想让它做更多的比较吗?

标签: c++ algorithm stl heap predicates


【解决方案1】:

我不会说存在足够标准化的算法,以至于您期望执行特定的比较集。 标准化的是算法的复杂性,只要比较的次数是线性的,你就可以开始了。此外,就比较次数而言,stl 的表现似乎比你好,所以你不必担心。

根据 cmets 的建议,您始终可以阅读编译器使用的 std::make_heap 实现的代码,但不能保证在所有 stl 实现中使用相同的实现。

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    相关资源
    最近更新 更多