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,就要用结构体重载排序函数了。然后再使用过程中,遇到了一些问题,也不知道为什么。

  • 相关阅读:
    gbk学习笔记
    在freebsd下编译nodejs,出现无法找到execinfo.h头文件的错误
    php 截取GBK文档某个位置开始的n个字符
    linux下,phpstorm配置oracle jdk
    gb2312学习笔记
    freebsd下vim默认的vi操作方式太难用,可通过启用vim自带配置文件解决
    freebsd通过ssh远程登陆慢,用户认证时间长解决办法
    php输出全部gb2312编码内的汉字
    visibility:hidden 与 display:none 的区别
    java 实现文件/文件夹复制、删除、移动(二)
  • 原文地址:https://www.cnblogs.com/dayq/p/11939324.html
Copyright © 2011-2022 走看看