priority_queue

模板定义

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

成员函数

  1. operator=  赋值给容器适配器
  2. top 访问栈顶元素
  3. empty 检查底层的容器是否为空
  4. size  返回容器的元素数
  5. push 插入元素并排序
  6. emplace(C++11)原位构造元素并排序
  7. pop 删除第一个元素
  8. swap 交换内容
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct ListNode{
	int val;
	ListNode* next;
	ListNode(int x): val(x), next(nullptr) {}
};

struct compare{
	bool operator()(const ListNode* l, const ListNode* r){
		return l->val > r->val;
	}
};

ListNode* mergeKLists(vector<ListNode*>& lists){
	priority_queue<ListNode*, vector<ListNode*>, compare> q;
	for(auto l: lists){
		if(l) q.push(l);
	}
	if(q.empty()) return NULL;

	ListNode* result = q.top();
	q.pop();
	if(result->next) q.push(result->next);
	ListNode* tail = result;
	while(!q.empty()){
		tail->next = q.top();
		q.pop();
		tail = tail->next;
		if(tail->next) q.push(tail->next);
	}
	return result;
}
#include <functional>
#include <queue>
#include <vector>
#include <iostream>

using namespace std;

template<typename T> void print_queue(T& q){
	while(!q.empty()){
		cout<<q.top()<<" ";
		q.pop();
	}
	cout<<'\n';
}

int main(){
	priority_queue<int> q;
	vector<int> qq {1,8,5,6,3,4,0,9,7,2};
	for(auto i = qq.begin(); i != qq.end(); ++i){
		q.push(*i);
	}
	print_queue(q);
	priority_queue<int, vector<int>, greater<int>> q2;
	for(auto i = qq.begin(); i != qq.end(); ++i){
		q2.push(*i);
	}
	print_queue(q2);

	//用lambda比较元素
	auto cmp = [](int left, int right) {return (left^1) <(right ^ 1);};
	priority_queue<int,vector<int>, decltype(cmp)> q3(cmp);
	for(auto i = qq.begin(); i != qq.end(); ++i){
		q3.push(*i);
	}
	print_queue(q3);
}

/*
9 8 7 6 5 4 3 2 1 0 
0 1 2 3 4 5 6 7 8 9 
8 9 6 7 4 5 2 3 0 1 
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值