c++ make_heap(), pop_heap()関数


c++のmake_heap(), pop_Heap()のヘッダファイルはalgorithmです.役割とpriority_queueのメンバー関数は同じで、単独で使用できます.
使用方法
make_heapは容器の範囲内で、その場でスタックを建てて、最大値が与えられた範囲の一番前にあることを保証して、その他の値の位置は確定しません
pop_Heapは、スタックトップ(与えられた範囲の一番前)要素を与えられた範囲の最後に移動し、新しい最大値を与えられた範囲の一番前に配置します.
push_Heapスタックのコンテナ範囲に新しい要素が挿入された後、push_を呼び出す必要があります.heapはこの要素をスタックに挿入します.
詳細は、次のコードを参照してください.
#include 
#include 
#include 
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;
    // pop max value
    pop_heap(nums.begin(), nums.end());
    nums.pop_back();
    cout << "after pop, the max vsalue : " << nums.front() << endl;
    // push a new value
    nums.push_back(6);
    push_heap(nums.begin(), nums.end());
    cout << "after push, the max value : " << nums.front() << endl;
    system("pause");
    return 0;
}
initial max value : 5
after pop, the max vsalue : 4
after push, the max value : 6

カスタム比較関数
スタックを構築する必要がある以上、要素間でサイズを比較したり、要素間の優先度を比較したりすることができます.比較関数が指定されていない場合は、デフォルトで呼び出されます.
次のコードは匿名関数で定義された比較関数であり,最小の要素をスタックトップに置くことができる.
#include 
#include 
#include 
using namespace std;

int main() {
    // define cmp function
    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);
    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;
    system("pause");
    return 0;
}
initial max value : 10
after pop, the max vsalue : 20
after push, the max value : 0

匿名関数のタイプはautoのみです.