6

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 of that class (vector<Person*>) and I want to compare the people by different parameters, for example age, length of name and so on.

I already have functions which return the needed variables but I am not sure how to do that. Here is a link to the sort vector function in the c++ reference http://www.cplusplus.com/reference/algorithm/sort/

1
  • @Ripounet if you are going to suggest edits to a question please fix everything not just the typo in the title. Take a look at the revisions to see what else needed to be fixed on this post Commented Jan 21, 2013 at 16:36

2 Answers 2

14

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.

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

2 Comments

Thanks! Please consider choosing the answer as the best if you feel it resolves your problem.
I will in 3 minutes after the system timer lets me.
-1

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

Comments

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.