首先按字母顺序排序数字列表,然后按数字排序

时间:2014-07-10 09:55:27

标签: c++ sorting comparison

我要求先按字母顺序对给定的数字进行排序,然后按数字顺序排序。 例如,我有这些数字

{"10", "1", "2", "20", "200", "3", "300", "30", "201", "21"}

我想要这个订单

{"1", "10", "2", "20", "21", "200", "201", "3", "30", "300"}

我编写了以下比较函数来对它们进行排序。

bool AlphaNumericCompare(const string & str1, const string& str2 )
{
    int ind1 = 0, ind2 = 0;
    while ( ind1 < str1.size() && ind2 < str2.size() )
    {
        if( str1[ind1] < str2[ind2] )
            return true;
        else if( str1[ind1] > str2[ind2] )
            return false;
        ind1++;
        ind2++;
    }
    if( ind1 == str1.size() && ind2 == str2.size() )
    {
        return true;
    }
    else if( ind1 == str1.size() )
    {
        return true;
    }
    return false;
}

但是这个功能给了我以下顺序

{"1", "10", "2", "20",  "200", "201", "21", "3", "30", "300"}

在21之前放置200和201。 有人可以建议如何更改上面的比较函数以获得所需的排序顺序吗?

2 个答案:

答案 0 :(得分:0)

使用自定义比较器功能对std::sort进行一次调用即可。像

这样的东西
std::sort(std::begin(collection), std::end(collection),
          [](const std::string& s1, const std::string& s2)
          {
              auto i1 = std::stoll(s1);
              auto i2 = std::stoll(s2);
              return (s1 < s2 && i1 < i2);
          });

请注意,它未经测试。

答案 1 :(得分:0)

如果我已正确理解任务,您希望首先按照第一个字符对数字进行分组,然后在这些组中进行排序。

这似乎可以完成这项工作:

std::sort(v.begin(), v.end(), [](const std::string& a, const std::string& b) {
    if (a[0] < b[0]) {
        return true;
    } else if (a[0] > b[0]) {
        return false;
    }
    return std::stoi(a) < std::stoi(b);
});

首先检查字符串的第一个字符。如果第一个字符相同,则执行数字排序。