简体   繁体   English

需要帮助理解 sort() c++ function 奇怪的行为

[英]Need help understanding the sort() c++ function weird behavior

I have a comparator function that compares two strings which represent numbers that have no leading zeros, eg "123" or "5".我有一个比较器 function,它比较两个表示没有前导零的数字的字符串,例如“123”或“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:除了字符串 nums 的向量之外,我还使用 sort() function,如下所示:

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"}这个 function 适用于这个向量: {"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:但是,如果我在向量中再添加一个“5”,它就会抛出这个:

terminate called after throwing an instance of 'std::length_error'在抛出“std::length_error”的实例后终止调用

what(): basic_string::_M_create what(): basic_string::_M_create

What is going on here?这里发生了什么?

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:或者,使用<tuple>工具确保严格的弱排序:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM