C/C++教程

cpp之priority_queue

本文主要是介绍cpp之priority_queue,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

cpp之priority_queue

  1. 大顶堆形式:priority_queue<int, vector, less>
  2. 小顶堆形式:priority_queue<int, vector, greater>

代码演示

int main() {
	int m;
	cin >> m;
	//小顶堆
	priority_queue<int, vector<int>, greater<int>>q_greater;
	//大顶堆
	priority_queue<int, vector<int>, less<int>>q_less;
	for (int i = 0; i < m; i++) {
		int temp;
		cin >> temp;
		q_greater.push(temp);
		q_less.push(temp);
	}
	cout << "greater is" << endl;
	for (int i = 0; i < m; i++) {
		cout << q_greater.top();
		q_greater.pop();
	}
	cout << endl;
	cout << "less is" << endl;
	for (int i = 0; i < m; i++) {
		cout << q_less.top();
		q_less.pop();
	}

	return 0;
}

输出结果:

如果要自定义一个比较形式:

要重写一个结构体进行符号重载

class Node {
public:
	int next[base] = { 0 };
	int data;
	bool operator () (Node* a,Node* b) {
		return a->data > b->data;
	}
};

class cmp {
public:
	bool operator () (Node* a, Node* b) {
		return a->data > b->data;
	}
};

int main() {
	int m;
	cout << "输入个数" << endl;
	cin >> m;
	cout << "---" << endl;
	priority_queue<Node*,vector<Node*>,cmp>q;
	for (int i = 0; i < m; i++) {
		int temp;
		cin >> temp;
		Node* n = new Node();
		n->data = temp;
		q.push(n);
	}
	cout << "greater is" << endl;
	for (int i = 0; i < m; i++) {
		cout << q.top()->data;
		q.pop();
	}
	return 0;
}

这篇关于cpp之priority_queue的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!