自然排序算法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;

}

相关推荐
clint4564 天前
C++进阶(1)——前景提要
c++
夜悊4 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴4 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0015 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾5 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you5 天前
constexpr函数
c++
凡人叶枫5 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫5 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss5 天前
BRpc使用
c++·rpc
-森屿安年-5 天前
63. 不同路径 II
c++·算法·动态规划