make_heap()用于将序列转换为堆。堆是指向最高(或最低)元素并在O(1)时间内进行访问的数据结构。所有其他元素的顺序取决于特定的实现,但始终保持一致。该函数在标题“ algorithm ”中定义。 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