自然排序算法1

#include <iostream>

#include <vector>

#include <algorithm>

#include <cctype>

#include <string>

// 比较两个字符串的自然排序的比较函数

bool naturalCompare(const std::string &a, const std::string &b) {

int i = 0, j = 0;

while (i < a.length() && j < b.length()) {

if (std::isdigit(ai) && std::isdigit(bj)) {

// 如果两个字符都是数字,则按数字的值进行比较

int valA = 0, valB = 0;

while (i < a.length() && std::isdigit(ai)) valA = valA * 10 + (ai++ - '0');

while (j < b.length() && std::isdigit(bj)) valB = valB * 10 + (bj++ - '0');

if (valA != valB) return valA < valB;

} else {

// 如果字符不是数字,则按字符的字典顺序进行比较

if (ai != bj) return ai < bj;

i++; j++;

}

}

return a.length() < b.length(); // 如果一个字符串是另一个字符串的前缀,则较短的字符串排在前面

}

int main() {

std::vector<std::string> strings = {"file10.txt", "file2.txt", "file1.txt", "file20.txt", "file3.txt"};

std::sort(strings.begin(), strings.end(), naturalCompare);

for (const auto &str : strings) {

std::cout << str << std::endl;

}

return 0;

}

相关推荐
Darkwanderor33 分钟前
Linux系统编程实战项目:模拟实现shell
linux·c++
himobrinehacken1 小时前
揭秘Windows程序启动的神秘之旅
c++·安全
库玛西2 小时前
C++ 运行时多态 :核心总结与原理图解
c语言·c++·笔记
Byron Loong3 小时前
【C++】重定向是什么
开发语言·c++
hansang_IR3 小时前
【题解】LC:Z 算法(Z Algorithm)
c++·算法·字符串
霍霍的袁5 小时前
【C++】模板从入门到进阶(函数模板 + 类模板 + 特化 + 分离编译)
开发语言·c++·visual studio
海清河晏1115 小时前
Qt 实战:信号与槽+事件系统
开发语言·c++·qt
hansang_IR5 小时前
【题解】LC:卷积(Convolution (Mod 1,000,000,007))
c++·算法·ntt·crt
啦啦啦啦啦zzzz5 小时前
设计模式:原型模式
c++·设计模式·原型模式
小保CPP6 小时前
OpenCV C++基于CNN模型的场景文本检测(OCR)
c++·人工智能·opencv·计算机视觉·cnn·ocr·光学字符识别