vector sort with objects?

后端 未结 2 1954
北海茫月
北海茫月 2021-01-03 04:59

So, in the c++ documentation in the header there is a nice function that lets you sort vectors. I have a class Person. I have a vector of pointers to objects o

2条回答
  •  -上瘾入骨i
    2021-01-03 05:16

    That's so simple:

    struct student
    {
      string name;
      string grade;
    };
    
    bool cmd(const student & s1, const student & s2)
    {
       if (s1.name != s2.name) return s1.name < s2.name;
       return s1.grade < s2.grade;
    }
    

    Then:

    vector s;
    sort(s.begin(), s.end(), cmd);
    

    Students will be sorted alphabatically. If two students have the same name, they will be ordered using their grade.

提交回复
热议问题