在不使用默认算法的情况下对字符串的 std 向量进行排序
sorting std vector of strings without using default algorithm
我有一个std::strings
std::vector
,每个都是一个文件名。假设文件名的格式为 some_name_n.xyz
.
问题是some_name_10.xyz
小于some_name_2.xyz
。这些文件是由其他一些进程生成的。
对它们进行排序的最不痛苦的方法是什么,以便考虑将"_"后面的数字进行比较,而不仅仅是其长度?
std::sort
允许您指定一个二进制函数来比较两个元素:http://www.cplusplus.com/reference/algorithm/sort/
现在只需构造该二进制函数即可。这里有一个部分示例:对包含数字的 std::字符串进行排序?
最不痛苦的方法是在文件名中加入适当的前导零(即使编写第二个脚本来获取生成的名称并重命名它们也可能比编写自己的排序例程更容易)。
第二种最不痛苦的方法是编写自己的排序谓词,该谓词将分隔_
数字排序为数字,而不是按字典顺序排序。
下面是处理字符串中嵌入的任意数量的数值的比较:
#include <cstdlib>
#include <cctype>
#include <iostream>
#ifdef _MSC_VER
#define strtoll _strtoi64
#endif
int cmp(const char* lhs, const char* rhs)
{
while (*lhs || *rhs)
{
if (isdigit(*lhs) && isdigit(*rhs))
{
char* l_end;
char* r_end;
long long l = strtoll(lhs, &l_end, 10);
long long r = strtoll(rhs, &r_end, 10);
if (l < r) return -1;
if (l > r) return 1;
lhs = l_end;
rhs = r_end;
}
else
if (*lhs != *rhs)
return *lhs - *rhs;
else
++lhs, ++rhs;
}
return *lhs - *rhs;
}
它故意是"C 样式",因此可以直接有效地应用于字符数组。 如果lhs < rhs
,则返回负数,如果它们相等,则返回 0,如果lhs > rhs
,则返回正数。
您可以从指定为 std::sort
的比较函子或 lambda 调用它。
您可以有一个自定义比较器,如下所示:
struct Comp{
auto get_num (const std::string& a)
{
auto it1 = std::find_if( a.begin(), a.end(), ::isdigit );
auto it2 = std::find_if( a.begin(), a.end(),
[](char x){ return x == '.' ;}) ;
/* Do some checks here for std::string::npos*/
auto pos1 = std::distance( a.begin(), it1) ;
auto pos2 = std::distance( it1, it2) ;
return std::stoi (a.substr( pos1, pos2 )) ;
}
bool operator () (const std::string& a, const std::string& b)
{
return get_num (a) < get_num (b) ;
}
};
在此处观看演示
相关文章:
- 我可以重新分配/覆盖std::字符串吗
- 如何将这个std::字符串转换为std::基本字符串
- std::字符串与 PCWSTR 的对话
- 重载 std::字符串运算符+ 用于打印枚举名称
- 从std::字符串创建OssBitString
- std::字符串擦除以删除最后一个字母
- 如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
- std::字符串串联操作
- 如何有效地将一个大std::字符串的一部分转换为float
- 转义std::字符串中的特殊字符
- 用C++替换std::字符串中的一个子字符串,但不能全部替换
- C++std::字符串流到常量字符*的转换
- 如何将std::字符串转换为不同的字符串类
- 对齐C++字符串类型问题 std::字符串到 TStr
- std::字符串到字符*而不切割字节
- 编写具有非ASCII数据的std ::字符串
- 将 Delphi 的字符串转换为 std::字符串用于C++
- std::字符串添加到字符*
- 字符* 和 std::字符串和常量字符*之间的转换
- 用指针访问std ::字符串中的元素