C++ 自定义对象 sort 排序

2023-12-13 06:29:42
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;
   });

文章来源:https://blog.csdn.net/qq_30505673/article/details/134941419
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。