c++中的push_heap函数做什么?
What does the push_heap function in C++ do?
我想知道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
的值压入堆中,将其移动到正确的位置以保持堆需求有效。它使用<
运算符来确定元素的顺序,或者使用用户指定的比较器。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 什么时候调用析构函数
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 是什么让放置新调用对象的构造函数?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 在C 中,对2D数组的增量是什么?函数断言(0)做什么?
- 我应该使用什么函数签名来返回对可能不存在的对象的引用
- 一个类的构造函数,为另一个类进行强制转换.将调用什么函数
- 在 opencv for c 中,什么函数与 Mat::convertTo 和 cvtColor() 完全相同
- 当按下Alt-Enter键时调用什么函数
- C库导出什么函数?
- 使用什么函数来选择文本
- c++在空类中编写和调用什么函数?
- 在共享库的构造函数(_init部分)中,如何知道什么函数被中断了?
- 我可以用什么函数来获取按钮的把手