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;    
    }
  • 相关阅读:
    Boost练习程序(program_options)
    vim一般设置
    删除文件夹及其子文件
    linux搜索一个文件
    窗口最大最小化
    3dmax 学习
    打造个人电脑安全终极防线
    Cacls Command Question
    vc++学习(六)——代码学习
    学习3dmax(四)
  • 原文地址:https://www.cnblogs.com/icfnight/p/3239097.html
Copyright © 2011-2022 走看看