String sort question

PLEASE LOOK INTO MY CODE AND TELL WHAT ERROR IS IN MY CODE

Share your code via ide.codingblocks.com

hi mridul gupta i mailed u this qns my code please see as ap

Apologies for a late response.
Hey i don’t find your code!
Please have a look at this very small snippet. Its very easy to understand the logic.

For this question you can make an array of strings and then sort it according to the condition that if there is a prefix match between two string, sort in decreasing order of length.

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.

#include#include#include<bits/stdc++.h>#includeusing namespace std;bool mycompare(string a,string b){ return (a.length()>b.length());}int main(){ int n; string arr[1000]; cin>>n; for(int i=0;i<n;i++){ cin>>arr[i]; } sort(arr,arr+n); int i=0; while(i<n){ vector v; string val=arr[i]; v.push_back(val); for(int j=i+1;j<n;j++){ int m=val.length(); if (arr[j].substr(0,m)==val){ v.push_back(arr[j]); i+=1; } } sort(v.begin(),v.end(),mycompare); for(int l=0;l<v.size();l++){ cout<<v[l]<<endl; } i=i+v.size(); v.clear(); }}

#3872610 is my submission id

Sort function is wrong.
What we should do is:

  1. First check character by character and the moment we find unequal, we return a boolean value.
  2. If all characters are same, return string of greater length.

bool compare(string a,string b)
{

for(int i=0;i<min(a.length(),b.length());i++)
{
    if(a[i]<b[i])
        return true;
    if(a[i]>b[i])
        return false;
}
return a.length()>b.length();

}

I hope i am clear now :slight_smile:

mai batata hu maine kya kiya hai phle sort kar liya array ko charcter ke basis par phir ye to obious hai ki abc hamesa abca ho ya abcda ho usse to phle hi aayega to hum phir length ke basis par sort kar dete hai .
ex (abc,baba,bac) ka o/p character ke basis par sort karne ke baad same as input aayega kyuki koi bhi kisi ka substring nhi hai or mai soch rha hu ki agar substring hogi to small substring hanesa uske string se phle hi hogi jab hum character ke basis par sort kar lenge .agar dikkat ho samajhne mai to please call at 8279454261 or provide your no bhai

I hope we are clear now.
You may close the doubt and mark it as resolved :slight_smile: