C++ 自定义对象 sort 排序

class Student {
    friend bool comp2(Student &i,Student &j);
public:
    Student(){
        this->Name = "wislon";
        this->Age = 12;
        this->Scodes = 90;
    }
    Student(string name ,int age,int scode){
        this->Age =age;
        this->Name =name;
        this->Scodes = scode;
    }
    void PrintStudent(){
        cout<< this->Name <<" "<<this->Age<<" "<<this->Scodes<<endl;
    }

private:
    int Age ;
    string Name ;
public:
    int Scodes;
};


bool comp2(Student &i,Student &j){
    if (i.Age > j.Age){
        return true;
    }
    return false;

}

int main() {
    Student *pStudent = new(Student);
    pStudent->PrintStudent();

    vector<Student> vs;
    vs.push_back(Student("x1",11,98));
    vs.push_back(Student("x2",12,90));
    vs.push_back(Student("x3",13,91));


   sort(vs.begin(),vs.end(), [](Student&a,Student&b)->bool {
       if (a.Scodes > b.Scodes){
           return true;
       }
       return false;
   });
    for  (auto v:vs){
        v.PrintStudent();
    }

    cout<<"*************"<<endl;

    sort(vs.begin(),vs.end(), comp2);
    for  (auto v:vs){
        v.PrintStudent();
    }
    cout<<"******3333333333*******"<<endl;
    return 0;
}

在这里插入图片描述

对私有成员变量排序
使用friend关键字 友元函数 进行 排序

 friend bool comp2(Student &i,Student &j);
 bool comp2(Student &i,Student &j){
    if (i.Age > j.Age){
        return true;
    }
    return false;

}

变量student中写 友元函数comp2 对私有属性Age进行排序

如果是public成员变量排序会非常简单

sort(vs.begin(),vs.end(), [](Student&a,Student&b)->bool {
       if (a.Scodes > b.Scodes){
           return true;
       }
       return false;
   });
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值