结构体重载运算符

本文通过一个简单的C++程序示例介绍了如何定义结构体并实现自定义排序功能。程序中定义了一个包含三个整型成员变量的结构体,并通过重载小于运算符实现了结构体数组的排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#define ll long long
#define inf 12345
using namespace std;
struct node{
    int x1,x2,h;
    bool operator < (const node& b) const{
        return h < b.h;   //或者写成 return this.h<b.h;
    }
}a[20010];
/*
bool operator < (const node &b1,const node &b2)
{
    return b1.h<b2.h;
}
*/
int main()
{
    a[0].x1=1;a[0].x2=1;a[0].h=1;
    a[1].x1=2;a[1].x2=2;a[1].h=2;
    a[2].x1=3;a[2].x2=3;a[2].h=3;
    sort(a, a+3);
    for(int i=0;i<3;i++)
    {
        cout<<a[i].x1<<" "<<a[i].x2<<" "<<a[i].h<<endl;
    }
}

//输出:
//1 1 1
//2 2 2
//3 3 3
 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值