zoukankan      html  css  js  c++  java
  • priority_queue里面自定义类型的使用。

     1 #include<iostream>
     2 #include<queue>
     3 using namespace std;
     4 struct tree{
     5     int num;
     6     string s;
     7     tree(int x,string zfc)
     8     {
     9         num=x;
    10         s=zfc;
    11     }
    12     friend bool operator>(const tree &a,const tree &b)
    13     {
    14         return a.num>b.num;
    15     }
    16     /* 显然用不用友元来重载是不一样滴*/ 
    17     /*bool operator<(const tree &a)const
    18     {
    19         return a.num>num;
    20     }*/
    21     bool operator==(const tree &a)const
    22     {
    23         return a.num>num;
    24     }
    25 };
    26 /* 两个重载的<,随便一个都可以,显然里面和外面重载参数个数是不同滴*/
    27 bool operator<(tree a,tree b)
    28 {
    29     return a.s<b.s;
    30 }
    31 int main()
    32 {
    33     priority_queue<tree> q;
    34     /* 因为要用到优先队列,所以必须重载<*/
    35     tree t(5,"hh");
    36     q.push(t);
    37     tree r(4,"xx");
    38     q.push(r);
    39     while(!q.empty())
    40     {
    41         cout<<q.top().num<<" "<<q.top().s<<endl;
    42         q.pop();
    43     }
    44     if(r==t)
    45     cout<<"hh";
    46     else
    47     cout<<"xx";
    48 }

    这是优先队列里面装一个普通的自定义类型。

     1 #include<iostream>
     2 #include<queue>
     3 using namespace std;
     4 typedef struct tree* T;
     5 struct tree{
     6     int num;
     7     string s;
     8     T next;
     9     tree(){
    10     }
    11     tree(int x,string zfc)
    12     {
    13         num=x;
    14         s=zfc;
    15     }
    16     friend bool operator<(const tree a,const tree b)
    17     {
    18         return b.num>a.num;
    19     }
    20 };
    21 struct cmp{
    22     bool operator()(T a,T b)
    23     {
    24         return a->num>b->num;
    25     }
    26 }; /* 使用结构体重载排序函数,priority_queue中就必须写好3个参数*/
    27 int main()
    28 {
    29 //    priority_queue<T,vector<T>,cmp> q;
    30     priority_queue<T> q;/* 不知道为啥,这里创造优先队列,没有重载排序函数,它也没有报错了*/
    31     T t=new tree();/* 指针类型必须分配空间*/
    32     t->num=5;
    33     t->s="hhh";
    34     q.push(t);
    35     T r=new tree();
    36     r->num=4;
    37     r->s="xxx";
    38     q.push(r);
    39     T h=new tree(3,"nn");
    40     q.push(h);
    41     while(!q.empty())
    42     {
    43         cout<<q.top()->num<<" "<<q.top()->s<<endl;
    44         q.pop();
    45     }
    46 } 

    要是用3个参数的priority_queue,就要用结构体重载排序函数了。然后再使用过程中,遇到了一些问题,也不知道为什么。

  • 相关阅读:
    How to install tcpping on Linux.md
    当前服务器的并发连接数查看
    Windows 系统下安装 dig 命令
    paping使用来测试联通&网站由于tcp协议导致的无法通信问题超时问题
    SSH反向连接及Autossh
    设置Windows Azure Linux虚拟机中的root账户
    用UltraISO制作CentOS U盘安装盘
    CentOS7 修改网卡名称为eth0
    iOS开发--绘图教程
    ios开发--网页中调用JS与JS注入
  • 原文地址:https://www.cnblogs.com/dayq/p/11939324.html
Copyright © 2011-2022 走看看