Unable to understand the output

Given the following code snippet :

bool comp(string s1, string s2)
{
if(s1.length() < s2.length())
return 1;
else if(s1.length() > s2.length())
return 0;
else return s1 < s2;
}

vector< string > data = {“b”, “a”, “c”, “abc”, “bca”, “xy”};
sort(data.begin(), data.end(), comp);
for(string item : data)
cout << item << " ";

Choose the correct output :

xy bca abc c b a

a b c xy abc bca

a b c abc bca xy

b a c xy abc bca

why a b c xy abc bca

why not a b c abc bca xy?

So your output is
a b c xy abc bca

  • This is because a is lexographically less then b
    b is lexographically less then c
  • Now xy length is greater then c, so xy comes(because of it’s greater length)
  • Since abc & bca have same length so we will see which is lexographically smaller. And you will see abc is lexographically smaller then bca, because of first letter in both the string, we can conclude a is lexographically shorter then b.

This is for lexographic order

This is for length if strings.

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.