0

Why does this code gives runtime error :

terminate called after throwing an instance of 'std:length_error' what(): basic_string::_M_create.

while changing the condition in comp function to s1.size() < s2.size() gives correct answer.

static bool comp(const string& s1,const string& s2){
    return s1.size()<=s2.size();
}

int main()
{
    int n;
    cin>>n;
    vector<string> words(n);
    for(int i=0;i<n;++i){
        cin>>words[i];
    }
    sort(words.begin(),words.end(),comp);
    for(int i=0;i<n;++i){
        cout<<words[i]<<" ";
    }
    return 0;
}
user438383
  • 5,716
  • 8
  • 28
  • 43
suthar0
  • 31
  • 3
  • 2
    The compare parameter for sort must satisfy the [*Compare* named requirement](https://en.cppreference.com/w/cpp/named_req/Compare) In your case it doesn't, so you get undefined behavour. The likely cause for your exact error is probably the iterator going past the end operator, since it relies e.g. on the fact that the `comp` relation is antireflexive – fabian Jun 15 '22 at 14:09
  • 2
    Change `s1.size()<=s2.size()` to `s1.size() – Drew Dormann Jun 15 '22 at 14:33

0 Answers0