如何使用字符串对对象向量进行排序

How can I sort a vector of objects using string?

本文关键字:排序 向量 对象 何使用 字符串      更新时间:2023-10-16

我有一个这样的类:

class student
{
    public:
    string name;
    int age;
    int rollnum;
    int year;
    string father;
    string mother;
    string category;
    string region;
    char sex;
    string branch;
    int semester;
};

我已经创建了这样一个类学生的向量(向量j1),现在我想根据他们的名字对他们进行排序。

我该怎么做?

附言:我做到了。

student lessthan
{
    bool operator() (const student& h1, const student& h2)
    {
        return (h1.name < h2.name);
    }
};

然后这样做,

sort(j1.begin(),j1.end(),lessthan());

但这显示了一个错误,在bool之前说预期的主表达式。

sort( j1.begin(),
     j1.end(),
     [](const student& s1, const student& s2){ return s1.name < s2.name;} );