Please tell me why its ans is 2 due to the comp function we have to arrange string in increasing length order so why we change b, a, c positions

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 << " ";
1.xy bca abc c b a

2.a b c xy abc bca

3.a b c abc bca xy

4.b a c xy abc bca

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 of string

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.