情形一(按字典序与长度增序排序)
- 得到一组字符串时,要求增序排序先比较长度,长度一致时比较字典序,字典序一致时再比较后面的数字
- 示例:
{"hello", "a2", "bw6", "hello1", "h3llo", "aa1", "c", "dasd2", "aa3"}
经过排序后为,("c", "a2", "aa1", "aa3", "bw6", "dasd2", "h3llo", "hello", "hello1")
。
QList<QString> lists = {"hello", "a2", "bw6", "hello1", "h3llo", "aa1", "c", "dasd2", "aa3"};
std::sort(lists.begin(), lists.end(), [=](QString &s1, QString &s2)
{
if (s1.length() != s2.length()) {
return s1.length() < s2.length();
}
int result = s1.localeAwareCompare(s2);
if (result != 0) {
return result < 0;
}
QRegularExpression re("\\d+");
QRegularExpressionMatch match1 = re.match(s1);
QRegularExpressionMatch match2 = re.match(s2);
if (match1.hasMatch() && match2.hasMatch()) {
int number1 = match1.captured().toInt();
int number2 = match2.captured().toInt();
return number1 < number2;
}
return match1.hasMatch() ? false : true; });
- 上述代码以qt为例,
localeAwareCompare
函数为QT特有用于比较字典序。在标准的 C++ 中,并没有直接等价的功能,因此要实现类似于 Qt 的 localeAwareCompare
函数,你需要依赖 C++ 库自己实现。
#include <string>
#include <locale>
int localeAwareCompare(const std::string& s1, const std::string& s2) {
const std::locale& loc = std::locale();
const std::collate<char>& coll = std::use_facet<std::collate<char>>(loc);
return coll.compare(s1.data(), s1.data() + s1.size(), s2.data(), s2.data() + s2.size());
}
- 在上面的代码中,
localeAwareCompare
函数使用默认的 locale (std::locale())
来获取 collate
对象,这个对象负责处理字符串的比较。collate::compare
函数用于比较范围内的两个字符串。
情形二(去重后排序)
- **去重问题很好解决,使用set**容器就可以实现了。
QSet<QString> uniqueSet(list.begin(), list.end());
QList<QString> uniqueList(uniqueSet.begin(), uniqueSet.end());
std::sort(uniqueList.begin(), uniqueList.end(), customLessThan);
customLessThan
即将情形一的排序函数封装一下。
情形三(待续)