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

}

相关推荐
肆忆_21 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马5 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼5 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛