C++ 自定义对象 sort 排序
  chunBooBRDn1 2023年12月22日 23 0


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 排序_友元函数

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


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

上一篇: c++ set 下一篇: c++ multimap
  1. 分享:
最后一次编辑于 2023年12月22日 0

暂无评论

推荐阅读
  8Tw5Riv1mGFK   2024年05月01日   78   0   0 C++
  BYaHC1OPAeY4   2024年05月08日   56   0   0 C++
  yZdUbUDB8h5t   2024年04月29日   56   0   0 C++
  yZdUbUDB8h5t   2024年05月05日   43   0   0 C++
  oXKBKZoQY2lx   2024年05月17日   56   0   0 C++