vector sort with objects?

后端 未结 2 1947
北海茫月
北海茫月 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条回答
  • 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<student> 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.

    0 讨论(0)
  • 2021-01-03 05:22

    Try to override operator like "<", ">" using the same properties of the objects. After that you can redefine some sort operation.

    0 讨论(0)
提交回复
热议问题