c++中的push_heap函数做什么?

What does the push_heap function in C++ do?

本文关键字:什么 函数 heap 中的 push c++      更新时间:2023-10-16

我想知道push_heap函数需要三个参数做什么?

#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;
class HeapCompare_f
    {
        public:
            bool operator() ( int x, int y ) const
            {
                return x > y;
            }
    };
int main()
{
    vector<int> vector1(5);
    for (int i = 0; i < 5; ++i)
        vector1[i] = 5-i;
    for (int i = 0; i < 5; ++i)
        cout << vector1[i];
    cout << endl;
    push_heap(vector1.begin(), vector1.end(),HeapCompare_f());
    for (int i = 0; i < 5; ++i)
        cout << vector1[i];
    cout << endl;

  return 0;
}

该代码的输出是

54321
15324

我也想知道如何在C中实现该函数?因为我将在A*算法中使用它我用C写的

您使用push_heap的方式不正确。

初始化vector后,需要将其按堆顺序排列:

std::make_heap(vector1.begin(), vector1.end());

要向堆中添加更多元素,需要首先将每个元素推到vector的后面,然后调用push_heap:

vector1.push_back(42);
std::push_heap(vector1.begin(), vector1.end());

最后,要删除堆中的第一个元素,需要调用pop_heap,然后从vector中取出最后一个元素:

std::pop_heap(vector1.begin(), vector1.end());
vector1.pop_back();

三个参数的堆函数允许你指定一个比较方法来控制堆的顺序,你做的是正确的。

手动调用push_back和pop_back的原因是堆函数只能看到容器中的迭代器,而不能访问容器本身。由于迭代器不足以修改容器的内容,因此必须由容器的所有者(您)手动完成。

为了避免自己处理这些问题,我建议使用std::priority_queue .

此函数不将一段值转换为堆!

std::push_heap(first, last [, comp])

假设范围[first,last-1)已经是一个有效的堆,并将位置last-1的值压入堆中,将其移动到正确的位置以保持堆需求有效。它使用<运算符来确定元素的顺序,或者使用用户指定的比较器。