优先队列:自定义优先级

priority_queue<Type, container,compare>
  • Type: Type of the elements.
  • Container: Type of the underlying container object used to store and access the elements
  • Compare: Comparison class: A class such that the expression comp(a,b), where comp is an object of this class and a and b are elements of the container, returns true if a is to be placed earlier than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function. This defaults to less<T>, which returns the same as applying the less-than operator (a<b).
    The priority_queue object uses this expression when an element is inserted or removed from it (using push or pop, respectively) to grant that the element popped is always the greatest in the priority queue.
优先队列默认<操作符,即元素值大的优先级高。
自定义优先级有2种方法:
     1、自定义compare类
     2、在struct或class中重载运算符
 
方法1:
#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct cmp
{
    bool operator()(int a,int b)
    {
        return a>b;    
    }      
};

int main()
{
    priority_queue<int,vector<int>,cmp> q;
    q.push(4);
    q.push(2);
    q.push(9);
    q.push(6);
   
    while(!q.empty())
    {
        cout<<q.top()<<" ";
        q.pop();               
    }
    cout<<endl;   
    system("pause");
    return 0;   
}

方法2:

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct node
{
    int v;
    bool operator<(node t) const
    {
        return v>t.v;     
    }       
}a[5];

int main()
{
    priority_queue<node> q;
    
    for(int i=5;i>=1;i--)
    {
        a[i].v=i;
        q.push(a[i]);        
    }
  
    while(!q.empty())
    {
        cout<<(q.top()).v<<" ";
        q.pop();                
    }
    cout<<endl;    
    system("pause");
    return 0;    
}
原文地址:https://www.cnblogs.com/icfnight/p/3239097.html