结构体符号重载

来源:互联网 发布:淘宝外穿铅笔裤 编辑:程序博客网 时间:2024/06/06 01:56
#include<stdio.h>#include<string.h>#include<algorithm>#include<queue>using namespace std;struct Point{int a;char str[105];bool operator < (const Point &other) const/*制定结构体与结构体比较时"<"的规则,不影响"<"的正常使用*/{if(a<other.a || a==other.a && strcmp(str, other.str)>0)return 1;/*重载后,sort时结构体按从小到大排序,优先队列顶端最大,可以直接用<来比较两个结构体大小*/return 0;}};Point s[10005];priority_queue<Point> q;int main(void){int i, n;scanf("%d", &n);for(i=1;i<=n;i++){scanf("%s%d", s[i].str, &s[i].a);q.push(s[i]);}sort(s+1, s+n+1);for(i=1;i<=n;i++)printf("%s %d\n", s[i].str, s[i].a);if(n>=2 && s[1]<s[2])printf("s[1]<s[2]\n");printf("the top is %s %d\n", q.top().str, q.top().a);return 0;}/*当且仅当结构体中重载"<"时sort和priority_queue才能使用,因为它们都用到了"<"而没有用到其他必要符号*/

0 0
原创粉丝点击