zoukankan      html  css  js  c++  java
  • C++之priority_queue

    1.优先队列priority_queue

             优先先队列是队列的一种,不过它可以按照自定义的一种方式(数据的优先级)来对队列中的数据进行动态的排序。每次的push和pop操作,队列都会动态的调整,以达到我们预期的方式来存储。常用的操作就是对数据排序,优先队列默认的是数据大的优先级高(即大根堆),即无论按照什么顺序push一堆数,top()总是能够弹出最大元素。

             常用有以下四种情况:普通大根堆和小根堆,自定义类型的大根堆和小根堆:

    #include <iostream>
    #include <queue>
    
    using namespace std;
    
    struct Node{
        int x;
        Node( int a= 0):x(a) {}
    	friend bool operator<(Node a,Node b ){
           return a.x<b.x;//  使用">"则为小根堆
        }
    };
    
    int main(){
    
    	int data2[5]={1,3,7,-4,56};
    	priority_queue<int> big(data2,data2+5);//大根堆
    	priority_queue<int,vector<int>,greater<int>> little(data2,data2+5);//小根堆。
    
            Node data1[10];
            for( int i= 0; i< 10; ++i )
               data1[i]=Node(rand());
    	priority_queue<Node> q(data1,data1+10);//自定义大根模式
    	
    	while(!big.empty()){
    		cout<<big.top()<<' ';
    		big.pop();
    	}
    	cout<<endl;
    
    
            while(!little.empty()){
    		cout<<little.top()<<' ';
    		little.pop();
            }
            cout<<endl;
    
            while( !q.empty() ){
                cout << q.top().x << ' ' ;
                q.pop();
           } 
    
        return 0;
    }
             对于三个参数的情况 "priority_queue<int,vector<int>,greater<int>>",第二个参数是存储容器,第三个是STL自带的仿函数

  • 相关阅读:
    泰国行记三:PP岛三天的休闲时光
    泰国行记二:普吉印象
    177. Nth Highest Salary
    176. Second Highest Salary
    175. Combine Two Tables
    Regular Expression Matching
    斐波那契数列
    用两个栈实现队列
    二叉树的下一个节点
    重建二叉树
  • 原文地址:https://www.cnblogs.com/engineerLF/p/5393007.html
Copyright © 2011-2022 走看看