【50 算法基础 C++】 make_heap(), pop_heap()函数

版权声明:欢迎转载,请注明来源 https://blog.csdn.net/linghugoolge/article/details/87867728

时间复杂度:O(n),在特殊要求情况下很有优势。

make_heap ()
在容器范围内,就地建堆,保证最大值在所给范围的最前面,其他值的位置不确定

pop_heap ()
将堆顶(所给范围的最前面)元素移动到所给范围的最后,并且将新的最大值置于所给范围的最前面

push_heap ()
当已建堆的容器范围内有新的元素插入末尾后,应当调用push_heap将该元素插入堆中。
 

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

int main() {
    vector<int> nums = {4, 5, 1, 3, 2};
    //默认最最小堆,可以添加比较函数
    // generate heap in the range of numsector
    make_heap(nums.begin(), nums.end());
    cout << "initial max value : " << nums.front() << endl;
    //5

    // pop max value
    pop_heap(nums.begin(), nums.end());
    nums.pop_back();
    cout << "after pop, the max vsalue : " << nums.front() << endl;
    //4

    // push a new value
    nums.push_back(6);
    push_heap(nums.begin(), nums.end());
    cout << "after push, the max value : " << nums.front() << endl;
    //6

    system("pause");
    return 0;
}

自定义比较函数

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

int main() {
    // define cmp function
    //注意匿名函数的类型只能是auto.
    auto cmp = [](const int x, const int y) { return x > y;};
    vector<int> nums2 = {40, 50, 10, 30, 20};

    // generate heap in the range of numsector
    make_heap(nums2.begin(), nums2.end(), cmp);
    //或者使用
    //make_heap(nums2.begin(), nums2.end(), greater<int>());
    cout << "initial max value : " << nums2.front() << endl;

    // pop max value
    pop_heap(nums2.begin(), nums2.end(), cmp);
    nums.pop_back();
    cout << "after pop, the max vsalue : " << nums2.front() << endl;

    // push a new value
    nums2.push_back(0);
    push_heap(nums2.begin(), nums2.end(), cmp);
    cout << "after push, the max value : " << nums2.front() << endl;

    //initial max value : 10
    //after pop, the max vsalue : 20
    //after push, the max value : 0

    system("pause");
    return 0;
}

答案

猜你喜欢

转载自blog.csdn.net/linghugoolge/article/details/87867728