Is the comparator function right? - String sort

#include<bits/stdc++.h>
using namespace std;

bool compare_rev(string a, string b){
if(a.compare(b)){
for(int i=0; i<b.length(); i++){
if(b[i]!=a[i]){
return a<b;
}
}
return b>a;
}
else if(b.compare(a)){
for(int i=0; i<a.length(); i++){
if(a[i]!=b[i]){
return a<b;
}
}
return a>b;
}

}
int main() {
int n;
cin>>n;
cin.get();
string s[n];
for(int i=0; i<n; i++){
getline(cin,s[i]);
}
sort(s,s+n,compare_rev);
for(int i=0; i<n; i++){
cout<<s[i]<<"\n";
}
return 0;
}

Hello @alien,

  1. How does a.compare(b) and b.compare(a) are different?
    Both of them will produce 0 if they a and b are same strings.

  2. if(b[i]!=a[i]) and if(a[i]!=b[i]) have same functonality.

  3. the condition after for loop doesn’t make any sense because that statement will execute only when all characters of both the string match completely i.e. a[i]==b[i] i.e. both are same strings.
    But, if they are the same strings, they would never satisfy the condition referred to in point 1.

Correct approach:

Hope, this would help.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.