jma*_*erx 9 c++ sorting string
我目前正在使用std :: string <运算符进行排序.问题在于:
30 <9.30显示在9 <9之前,Windows 9x有此问题.我怎样才能在数字上对它们进行排序,以便在"9只狗"之后出现"30只狐狸".我还应该补充一点,我正在使用utf 8编码.
谢谢
您可以创建要使用的自定义比较函数std::sort
.此函数必须检查字符串是否以数字值开头.如果是这样,请int
使用某种机制(如stringstream)将每个字符串的数字部分转换为a.然后比较两个整数值.如果值相等,则按字典顺序比较字符串的非数字部分.否则,如果字符串不包含数字部分,只需按字典顺序比较两个字符串即可.
基本上,类似于以下(未经测试的)比较功能:
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());
}
Run Code Online (Sandbox Code Playgroud)
然后...
std::sort(string_array.begin(), string_array.end(), numeric_string_compare);
Run Code Online (Sandbox Code Playgroud)
编辑:当然,这个算法只有在排序数字部分出现在字符串开头的字符串时才有用.如果您正在处理字符串,其中数字部分可以出现在字符串中的任何位置,那么您需要更复杂的算法.有关更多信息,请访问http://www.davekoelle.com/alphanum.html.