• 优先队列 C++


    1.头文件:include<queue>

    2.定义:优先队列和队列一样,只能从队尾插入元素,从队首删除元素。队列中最大的元素总是位于队首。可以通过重载<运算符来重新定义比较规则。

    3.优点:自动排序

    4.声明:priority_queue<数据类型> 队列名;

    5.常用的声明:

    5.1基本常量的优先队列:

    priority_queue<int> q1;
    priority_queue<double> q2;

    5.2常用的优先队列:

    priority_queue <int,vector<int> ,greater<int> > q;//使元素按照从小到大顺序出队 
    priority_queue <int,vector<int> ,less<int> > q2;//降序排列 ,无需声明vector头文件
    5.3自定义结构体优先队列
    #include<iostream>
    #include<queue> 
    using namespace std;
    struct Node{
    	int id;
    	int x;
    }; 
    bool operator < (const Node &a,const Node &b){
    		return a.id<b.id;
    }
    int main()
    {
    	priority_queue<Node> q;
    	return 0;
    }

    6.常用操作:

    empty()    如果队列为空,则返回真

    pop()    删除队列第一个元素

    push()    加入一个元素

    size()    返回队列的元素个数

    top()    取队顶元素

    7.测试代码:

    #include<iostream>
    #include<queue> 
    using namespace std;
    struct Node{
    	int id;
    	int x;
    	Node (int id,int x):id(id),x(x){}
    	void print(){
    		cout << id << " " << x << endl;
    	}
    }; 
    bool operator < (const Node &a,const Node &b){
    		return a.id < b.id;
    }
    int main()
    {
    	priority_queue<Node> q;
    	int id,x;
    	do{
    		cin >> id >> x;
    		q.push(Node(id,x));
    	}while(id != 0);
    	while(!q.empty()){
    		Node a = q.top();
    		q.pop();
    		a.print();
    	}
    	return 0;
    }


  • 相关阅读:
    python编程学习进度七
    python编程学习进度六
    SOA——2020.5.15
    代码大全001/
    Refined Architecture阶段——细化架构
    架构即未来003(摘自网络)
    我对外包公司的小小看法
    架构即未来002
    每日日报
    架构即未来阅读笔记001
  • 原文地址:https://www.cnblogs.com/long98/p/10352242.html
Copyright © 2020-2023  润新知