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;    
    }
  • 相关阅读:
    Js使用WScript.Shell对象执行.bat文件和cmd命令
    wscript运行js文件
    Linux基础tree命令
    使用libssh2库实现支持密码参数的ssh2客户端
    zlib库剖析(1):实现概览
    Linux设置编译器环境变量
    开源的zip_unzip库
    黑客入门之单机游戏外挂
    linux定时任务的设置 crontab 配置指南
    Linux crontab定时执行任务 命令格式与详细例子
  • 原文地址:https://www.cnblogs.com/icfnight/p/3239097.html
Copyright © 2011-2022 走看看