make_heap() 用于将序列转换为堆。堆是一种数据结构,它指向最高(或最低)元素并在O(1)时间内进行访问。所有其他元素的顺序取决于特定的实现,但始终保持一致。该函数在标题“算法”中定义。 make_heap()函数有两种实现。两者都通过本文进行了解释。语法 1 : make_heap(iter_first, iter_last)
Template :
void make_heap (RandomAccessIterator first, RandomAccessIterator last);
Parameters :
first : The pointer to the starting element of sequence that has to
be transformed into heap.
last : The pointer to the next address to last element of sequence that
has to be transformed into heap.
下面是演示代码:
// C++ code to demonstrate the working of
// make_heap() using syntax 1
#include
#include // for heap
#include
using namespace std;
int main()
{
// initializing vector;
vector vi = { 4, 6, 7, 9, 11, 4 };
// using make_heap() to transform vector into
// a max heap
make_heap(vi.begin(),vi.end());
//checking if heap using
// front() function
cout << "The maximum element of heap is : ";
cout << vi.front() << endl;
}
输出:
The maximum element of heap is : 11
语法 2 : make_heap(iter_first, iter_last, comp)
Template :
void make_heap (RandomAccessIterator first, RandomAccessIterator last, comp);
Parameters :
first : The pointer to the starting element of sequence that has to be transformed into heap.
last : The pointer to the next address to last element of sequence that has to be transformed into heap.
comp : The comparator function that returns a boolean true/false of the each elements compared. This function accepts two arguments. This can be function pointer or function object and cannot change values.
下面是演示代码:
// C++ code to demonstrate the working of
// make_heap() using syntax 2
#include
#include // for heap
#include
using namespace std;
// comparator function to make min heap
struct greaters{
bool operator()(const long& a,const long& b) const{
return a>b;
}
};
int main()
{
// initializing vector;
vector vi = { 15, 6, 7, 9, 11, 45 };
// using make_heap() to transform vector into
// a min heap
make_heap(vi.begin(),vi.end(), greaters());
// checking if heap using
// front() function
cout << "The minimum element of heap is : ";
cout << vi.front() << endl;
}
输出:
The minimum element of heap is : 6
可能的应用:此函数可用于调度。在调度中,在迭代中动态插入一个新元素。一次又一次地排序以获得最大的复杂度 O(nlogn),而不是我们使用“push_heap()”函数来堆化在 O(logn) 时间内产生的堆。下面的代码描述了它的实现。
// C++ code to demonstrate
// application of make_heap() (max_heap)
// priority scheduling
#include
#include // for heap
#include
using namespace std;
int main()
{
// initializing vector;
// initial job priorities
vector vi = { 15, 6, 7, 9, 11, 19};
// No. of incoming jobs.
int k = 3;
// using make_heap() to transform vector into
// a min heap
make_heap(vi.begin(),vi.end());
// initializing job variable
int a = 10;
for ( int i=0; i
输出:
Job with maximum priority is : 19
Job with maximum priority is : 20
Job with maximum priority is : 30
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。