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;
}

C++ 自定义对象 sort 排序_第1张图片

对私有成员变量排序
使用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;
   });

你可能感兴趣的:(c++,前端)