zoukankan      html  css  js  c++  java
  • 优先队列:自定义优先级

    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;    
    }
  • 相关阅读:
    Servlet----------在 Servlet 中的xml配置
    java连接数据库时的报错
    借用HTML5 插入视频。音频
    多线程的总结
    穷举法例子
    利用递归求最大公约数和最小公倍数
    递归逆序的使用
    Mac OS X运行程序出现bad interpreter: operation not permitted的解决方案
    C#之枚举类型
    窗体的单例模式
  • 原文地址:https://www.cnblogs.com/icfnight/p/3239097.html
Copyright © 2011-2022 走看看