0

Imagine class with string value.

class Test {
public:
    string name;
};

Is is stored in vector

vector<Test> d;

I would like to use sort() function to sort objects in vector alphabeticaly by its name value. I know that sort() function has third parameter some kind of sorting function but i dont know how to write this function.

sort(d.begin(),d.end(),comp());

comp () { ? }
1
  • 1
    References are generally very good for this sort of thing. Commented Mar 9, 2014 at 19:50

2 Answers 2

2

You can create a comparator

bool comp(const Test &test1, const Test &test2){
    return test1.getName() <  test2.getName();
}

Or you can overload the operator < in your class

bool operator < (const Test &test){
    return name < test.name;
}

Note that if you overload the operator <, then you don't need to add the third parameter in the sort function.

Sign up to request clarification or add additional context in comments.

1 Comment

@Paranaix, Yes, any callable object.
0

comp will be a function that will return a bool to indicate the comparison in two parameters. In your case, it should look like:

bool compare ( const Test& s1, const Test& s2 )
{
    return ( s1.name < s2.name );
}

and your call will be: sort ( d.begin(), d.end(), compare );

1 Comment

I believe it is preferable to use const Test& s1 instead of simply Test s1 for the parameters to avoid copying the object.

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.