Stable Sort

I have a program where I am given a large file of UC students that already sorted by ID. I need to sort it by the school they are attending and students attending the same school to be sorted by ID in ascending order.

ie. Joe Paarmann,3,UCB

I need to implement a given function

bool compareBySchoolName(Student s1, s2) which compares two students by school name
it should return true if and only if s1 school comes before (is less than) s2 school

and use the sort function
sort(students,students+ len, compareBySchoolName);

My problem is how do I compare school names since they are strings? I'm confused how to start this. Thank you any help is very much appreciated.

1
2
3
4
5
6
7
8
  /*
 * Compare two students by school name
 * Return true if and only if s1 school comes before s2 school
 */
bool compareBySchoolName(Student s1, Student s2) {
	// your code here
}
My problem is how do I compare school names since they are strings?

Are they c-style strings or objects of type std::string?
Last edited on
They are s objects of type std::string
Then:

1
2
3
4
 bool compareBySchoolName(const Student& a, const Student& b)
{
    return a.name < b.name;
}


Assuming you replace name with the actual variable identifier or a call to the appropriate accessor function.
What troubles me is than when it compares school its just comparing the length of the strings corrrect? is there a way it can compare school names alphabetically?

for example UCB < UCD?
What troubles me is than when it compares school its just comparing the length of the strings corrrect?

That shouldn't trouble you, because that isn't what it's doing.

is there a way it can compare school names alphabetically?
std::string comparisons are done lexicographically.
Oh alright thank you so much!
and use the sort function
sort(students,students+ len, compareBySchoolName);

If you want stable sorting shouldn't you use std::stable_sort?
http://en.cppreference.com/w/cpp/algorithm/stable_sort
Topic archived. No new replies allowed.