简体   繁体   English

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

[英]How can I sort a vector of objects using string?

I have a class like this: 我有这样的课:

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

I have created a vector (vector j1) of such class student, and now I want to sort them on the basis of their name. 我创建了一个此类学生的向量(向量j1),现在我想根据他们的名字对它们进行排序。

How can I do that? 我怎样才能做到这一点?

PS: I did this. PS:我做到了。

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

And then did this, 然后做到了

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

But this shows an error saying expected primary expression before bool. 但这显示了一个错误,说期望的主表达式在布尔之前。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM