简体   繁体   中英

How do I compare two strings?(less than)

I have a program in C++ where I am given a large file of UC students that already sorted by ID . I need to sort it by the school name 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.

bool compareBySchoolName(Student s1, Student s2) { 
}

you can, you need to make up your mind as to how you are going to compare the strings. I suggest you use alphabetical order of words from left to right. you can't implement logic if you don't know what logic you want to implement :).

You can do following,

a.compareTo(b); //where a and b are your two strings

It will return a integer value and based on that you can decide. More info here

Just compare it if you are using C++ string C++ String Relational Operators

 bool compareBySchoolName(Student s1, Student s2) { return s1.schoolName < s2.schoolName || (s1.schoolName == s2.schoolName && s1.ID < s2.ID); } 

different language have different comparator function.When you use comparator function, it will be get return int value . So You use < or > in return satement and get true or false .

In C++, You can do this like:

bool compareBySchoolName(Student s1, Student s2) {
    return s1.schoolName < s2.schoolName || (s1.schoolName == s2.schoolName && s1.ID < s2.ID) 

}

Ok Buddy, from this reference: http://www.cplusplus.com/reference/algorithm/sort/

you can see that the comp parameter does the following:

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

So all you have to do is

bool compareBySchoolName(Student s1, Student s2) { 
return s1.SchoolName< s2.SchoolName;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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