Data structure learning: heap and priority_queue

Preliminary study of the examples of the
heap In addition to the realization of the large top heap and the small top heap, you can directly use the priority_queuecontainer in the STL .

The easy-to-understand code is as follows:

#include<iostream>
#include<algorithm>
#include<queue>
#include<functional>

using namespace std;

int main()
{
    
    
	priority_queue<int, vector<int>, less<int>> p;//大顶堆:这个等同于priority_queue<int>
	p.push(3);	//p:3
	p.push(4);	//p:43
	p.push(2);	//p:432
	p.push(5);	//p:5423    /*注意这里并不是5432,故没有严格排序,但堆顶可以确保*/
	p.push(1);	//p:54321

	int getp = p.top();	//getp取得堆顶元素5,堆不是front,而是top!

	p.pop();	//p:4321
	p.pop();	//p:312     /*注意这里并不是321,故没有严格排序,但堆顶可以确保*/
	p.pop();	//p:21
	p.pop();	//p:1
	p.pop();	//p

	priority_queue<int, vector<int>, greater<int>> q;//小顶堆
	q.push(3);	//q:3
	q.push(4);	//q:34
	q.push(2);	//q:243     /*注意这里并不是234,故没有严格排序,但堆顶可以确保*/
	q.push(5);	//q:2435    /*注意这里并不是2345,故没有严格排序,但堆顶可以确保*/
	q.push(1);	//q:12354   /*注意这里并不是12345,故没有严格排序,但堆顶可以确保*/

	int getq = q.top();	//getp取得堆顶元素1,堆不是front,而是top!

	q.pop();	//q:2435    /*注意这里并不是2345,故没有严格排序,但堆顶可以确保*/
	q.pop();	//q:345
	q.pop();	//q:45
	q.pop();	//q:5
	q.pop();	//q

	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42979679/article/details/103848370