自然排序算法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(a[i]) && std::isdigit(b[j])) {

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

int valA = 0, valB = 0;

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

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

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

} else {

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

if (a[i] != b[j]) return a[i] < b[j];

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;

}

相关推荐
CSDN_RTKLIB9 分钟前
C++取余符号%
开发语言·c++
WBluuue20 分钟前
Codeforces Good Bye 2025 Div1+2(ABCDE)
c++·算法
明洞日记1 小时前
【VTK手册034】 vtkGeometryFilter 深度解析:高性能几何提取与转换专家
c++·图像处理·算法·ai·vtk·图形渲染
额呃呃1 小时前
operator new/delete
开发语言·c++·算法
平生不喜凡桃李1 小时前
Google C++ Style Guide : 变量与函数名
开发语言·c++·google c++
HL_风神1 小时前
设计原则之单一职责原则
c++·学习·设计模式·单一职责原则
linzihahaha1 小时前
C++ 单例模式总结
开发语言·c++·单例模式
一个不知名程序员www2 小时前
算法学习入门--- set与map(C++)
c++·算法
小此方2 小时前
Re: 从零开始的C++ 入門(十)类和对象·最终篇下:类型转换、static成员、友元、匿名对象、内部类、拷贝编译优化
开发语言·c++·底层
王老师青少年编程2 小时前
2025年12月GESP(C++)考级真题及详细题解(汇总版)
c++·题解·真题·gesp·csp·信奥赛·考级