我目前正在按 std::string
30
Thanks
您可以创建自定义比较函数来使用std::sort
。该函数必须检查字符串是否以数值开头。如果是,则将每个字符串的数字部分转换为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, s1.end(), it2, s2.end());
}
进而...
std::sort(string_array.begin(), string_array.end(), numeric_string_compare);
编辑:当然,只有当您对数字部分出现在字符串开头的字符串进行排序时,此算法才有用。如果您正在处理可能出现数字部分的字符串anywhere在字符串中,那么你需要一个更复杂的算法。看http://www.davekoelle.com/alphanum.html http://www.davekoelle.com/alphanum.html了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)