Home > front end >  Need help understanding the sort() c function weird behavior
Need help understanding the sort() c function weird behavior

Time:10-13

I have a comparator function that compares two strings which represent numbers that have no leading zeros, eg "123" or "5".

bool comp(string s1,string s2){
    if(s1.size()!=s2.size())
        return s1.size()<s2.size();

    int i=0;
    while(i<s1.size() && s1[i]==s2[i])
        i  ;

    if(i==s1.size())
        return true;

    return s1[i]<s2[i]; 
}

Along with a vector of strings nums I use the sort() function like this:

sort(nums.begin(),nums.end(),comp);

And this function will work for this vector: {"5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5"}

But if I add one more "5" to the vector it throws this:

terminate called after throwing an instance of 'std::length_error'

what(): basic_string::_M_create

What is going on here?

CodePudding user response:

Your comparer doesn't respect strict weak ordering,

equality checked by

if (i == s1.size())
    return true;

should be

if (i == s1.size())
    return false;

Alternatively, using <tuple> facility ensures strict weak ordering:

bool comp(const std::string& s1, const std::string& s2)
{
    return std::forward_as_tuple(s1.size(), s1)
         < std::forward_as_tuple(s2.size(), s2);
}
  • Related