0

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.

How can I do that?

PS: I did this.

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.

3
  • lessthan should be a class/struct. typo about student ? Commented Aug 31, 2014 at 16:30
  • student should be struct. Commented Aug 31, 2014 at 16:31
  • char sex; This is not exactly type-safe. It supposedly allows for 'M' and 'F'. Or 'm' and 'f'? Or both? What if someone accidentally assigns 'a' or 'b', or 123 or 255 or 0? You should at least use an enum. Commented Aug 31, 2014 at 16:34

1 Answer 1

3
sort( j1.begin(),
     j1.end(),
     [](const student& s1, const student& s2){ return s1.name < s2.name;} );
Sign up to request clarification or add additional context in comments.

2 Comments

begin(j1) instead of j1.begin() to be slightly more idiomatic.
Might want to explain that's a lambda.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.