C++中的MaxIHEAPE()

make_heap()用于将序列转换为堆。堆是一种数据结构 指向最高点 (或最低)元素,并在 O(1) 时间所有其他元素的顺序取决于具体的实现,但始终保持一致。此函数在标题中定义“ 算法 “。make_heap()函数有两种实现。本文将对这两种实现进行解释。 语法1:make_heap(首先是iter_,最后是iter_)

null

模板: void make_heap(首先是RandomAccessIterator,最后是RandomAccessIterator); 参数: 第一 :指向必须删除的序列的起始元素的指针 被转化成堆。 最后的 :指向该序列最后一个元素的下一个地址的指针 必须转换成堆。

下面是演示代码:

// C++ code to demonstrate the working of
// make_heap() using syntax 1
#include<iostream>
#include<algorithm> // for heap
#include<vector>
using namespace std;
int main()
{
// initializing vector;
vector< int > 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_优先,iter_最后,comp)

模板: void make_heap(首先是RandomAccessIterator,最后是RandomAccessIterator,comp); 参数: 第一 :指向必须转换为堆的序列的起始元素的指针。 最后的 :指向必须转换为堆的序列最后一个元素的下一个地址的指针。 公司: comparator函数,返回所比较的每个元素的布尔真/假。此函数接受两个参数。这可以是函数指针或函数对象,不能更改值。

下面是演示代码:

// C++ code to demonstrate the working of
// make_heap() using syntax 2
#include<iostream>
#include<algorithm> // for heap
#include<vector>
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< int > 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<iostream>
#include<algorithm> // for heap
#include<vector>
using namespace std;
int main()
{
// initializing vector;
// initial job priorities
vector< int > 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<k; i++)
{
// push a job with priority level
vi.push_back(a);
// transform into heap ( using push_heap() )
push_heap(vi.begin(), vi.end());
//checking top priority job
// front() function
cout << "Job with maximum priority is : " ;
cout << vi.front() << endl;
// increasing job priority level
a = a + 10;
}
}


输出:

Job with maximum priority is : 19
Job with maximum priority is : 20
Job with maximum priority is : 30

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享