日常开发中排序操作是很常见的,大多时候使用qSort默认方式,就可以满足需求;
但是遇到字符串中包含1、2、3、10、11、12、21、22、31这种时,顺序就会乱掉;
目前我遇到的情况是:
DLC-30A/50A
DLC-30A/50A_2.2
DLG-30A_1
DLG-30A_2
DLT-30A
Remote-auto-1
Remote-auto-2
Remote-auto-3
Remote-auto-4
Remote-auto-5
Remote-auto-6
Remote-auto-7
Remote-auto-8
Remote-auto-9
Remote-auto-10
Remote-auto-11
Remote-auto-12
Remote-auto-13
Remote-auto-14
Remote-auto-15
Remote-auto-16
Remote-auto-17
Remote-auto-18
Remote-auto-19
Remote-auto-20
Remote-auto-21
Remote-18004
def1
multi_cast
按照正常的排序算法,得到的可能是如下的字符串:
DLC-30A/50A
DLC-30A/50A_2.2
DLG-30A_1
DLG-30A_2
DLT-30A
Remote-18004
def1
multi_cast
Remote-auto-1
Remote-auto-10
Remote-auto-11
Remote-auto-12
Remote-auto-13
Remote-auto-14
Remote-auto-15
Remote-auto-16
Remote-auto-17
Remote-auto-18
Remote-auto-19
Remote-auto-2
Remote-auto-20
Remote-auto-21
Remote-auto-3
Remote-auto-4
Remote-auto-5
Remote-auto-6
Remote-auto-7
Remote-auto-8
Remote-auto-9
为了将其按照最后面数字进行正确排序,可以使用如下算法:
void SortDSName(QStringList& names)
{
std::sort(names.begin(), names.end(),[](QString &mIt, QString &nIt){
QStringList mStr=mIt.mid(1).split(".");
QStringList nStr=nIt.mid(1).split(".");
int num = mStr.length() < nStr.length() ? mStr.length() : nStr.length();
for(int i = 0; i < num; i++)
{
//if(mStr[i].toInt() == nStr[i].toInt())
if(mStr[i] == nStr[i]) {
continue;
} else {
return mStr[i].toInt() < nStr[i].toInt();
}
}
return mStr.length() < nStr.length();
});
}