heap - Heap

1, C ++ STL in the heap (heap) is a data structureComplete binary tree. In the standard library heap algorithm is algorithm header file, provides several functions operate as follows.

The following functions are third parameter default maximum heap parameters. To use the minimum heap, you need to explicitly set the third parameter greater

  • make_heap (): according to the specified iterator range to create a heap.
vector<int> v = { 10,20,5,60 };

// 创建最大堆,默认是创建最大堆。该堆的最大元素为二叉树根节点的元素 v[0]或v.front()
make_heap(v.begin(), v.end(), less<int>());
// 创建最小堆,该堆中根节点的元素最小
make_heap(v.begin(), v.end(), greater<int>());

  • push_heap (): the last iteration interval a specified element is inserted into the heap, and is often used in conjunction with vector.
v.push_back(100);
push_heap(v.begin(), v.end(),less<int>()); //将容器末尾的值插入到堆的合适位置.

  • pop_heap: specifies the last element in the iteration area placed at the end of the container
// 将最大堆中的根节点元素置于容器的尾部,并未删除
pop_heap(v.begin(), v.end(), less<int>()); 
v.pop_back();//删除容器末尾的元素。

  • sort_heap: heap sort

2, the following sample code

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
	int arr[] = { 10,20,3,40,18 };
	int len = sizeof(arr) / sizeof(arr[0]);
	vector<int> vec(arr, arr + len); //用数组来初始化容器

	make_heap(vec.begin(), vec.end()); //以容器vec中的元素来建立堆,默认是最大堆
	cout << "The max heap: " << vec.front() << '\n';// 首元素为容器中的最大值

	pop_heap(vec.begin(), vec.end());//将迭代器区间中的最大元素置于vector容器的末尾
	vec.pop_back();//将此最大值删除
	cout << "max heap after pop: " << vec.front() << '\n';

	vec.push_back(99);//向容器末尾插入值
	push_heap(vec.begin(), vec.end());//将指定区间的最后一个元素插入到heap中
	cout << "max heap after push: " << vec.front() << '\n';

	sort_heap(vec.begin(), vec.end());//对堆进行排序

	cout << "final sorted range: ";
	for (auto &i:vec)
	{
		cout << i << " ";
	}

	cout << endl;
	system("pause");


}

Output:
Here Insert Picture Description


Reference:
STL - heap structure and algorithm
make_heap
C ++ standard library heap (heap)
STL heap in the correlation function

Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104703706