加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 对带有数字的std :: strings进行排序?

发布时间:2020-12-16 04:54:08 所属栏目:百科 来源:网络整理
导读:我目前正在按std :: string排序操作符.问题在于: 30 9. 30显示在9之前,因为3 9,Windows 9x有这个问题.我怎么能在数字上对它们进行排序,以便在“9只狗”之后出现“30只狐狸”.我还应该补充说我正在使用utf 8编码. 谢谢 解决方法 您可以创建自定义比较函数以
我目前正在按std :: string<排序操作符.问题在于: 30< 9. 30显示在9之前,因为3< 9,Windows 9x有这个问题.我怎么能在数字上对它们进行排序,以便在“9只狗”之后出现“30只狐狸”.我还应该补充说我正在使用utf 8编码.

谢谢

解决方法

您可以创建自定义比较函数以与std :: sort一起使用.此函数必须检查字符串是否以数字值开头.如果是这样,使用像stringstream这样的机制将每个字符串的数字部分转换为int.然后比较两个整数值.如果值相等,则按字典顺序比较字符串的非数字部分.否则,如果字符串不包含数字部分,只需按字典顺序比较两个字符串即可.

基本上,类似于以下(未经测试的)比较功能:

bool is_not_digit(char c)
{
    return !std::isdigit(c);
}

bool numeric_string_compare(const std::string& s1,const std::string& s2)
{
    // handle empty strings...

    std::string::const_iterator it1 = s1.begin(),it2 = s2.begin();

    if (std::isdigit(s1[0]) && std::isdigit(s2[0])) {
        int n1,n2;
        std::stringstream ss(s1);
        ss >> n1;
        ss.clear();
        ss.str(s2);
        ss >> n2;

        if (n1 != n2) return n1 < n2;

        it1 = std::find_if(s1.begin(),s1.end(),is_not_digit);
        it2 = std::find_if(s2.begin(),s2.end(),is_not_digit);
    }

    return std::lexicographical_compare(it1,it2,s2.end());
}

然后…

std::sort(string_array.begin(),string_array.end(),numeric_string_compare);

编辑:当然,这个算法只有在排序数字部分出现在字符串开头的字符串时才有用.如果你正在处理数字部分可以出现在字符串中任何位置的字符串,那么你需要一个更复杂的算法.有关更多信息,请参见http://www.davekoelle.com/alphanum.html.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读