C++ - 以特定方式对 vector 中的字符串进行排序

标签 c++ string sorting vector

我目前正在尝试对 vector 中的字符串进行排序,但我不确定如何以特定的方式进行排序。我正在使用的游戏引擎要求对字符串进行不区分大小写的排序(我已经能够完成)。它还对这些文件名进行排序,并在字母之前添加下划线。

例如,这些字符串当前排序如下:

ChallengeBattleships.bsf
ChallengeBattleships.zip
ChallengeBattleshipsPause.bsf
ChallengeBattleshipsSummary.bsf
ChallengeBattleshipsSurface.bsf
ChallengeBattleships_arena.bsf
ChallengeBattleships_day.zip

但我需要它们像这样排序(以及不区分大小写):

ChallengeBattleships.bsf
ChallengeBattleships.zip
ChallengeBattleships_arena.bsf
ChallengeBattleships_day.zip
ChallengeBattleshipsPause.bsf
ChallengeBattleshipsSummary.bsf
ChallengeBattleshipsSurface.bsf

有人知道如何以这种方式对 vector 中的字符串进行排序吗?

最佳答案

将 std::sort 与 lambda 一起使用。 如果不修改原始字符串则:

std::sort(vec.begin(), vec.end(), 
         [](std::string s1, std::string s2){
             std::transform(s1.begin(), s1.end(), s1.begin(),
                   [](char c){ return std::tolower(c); });
             std::transform(s2.begin(), s2.end(), s2.begin(),
                   [](char c){ return std::tolower(c); });
             return s1 < s2;
         });

要更改大小写: How to convert std::string to lower case?

关于C++ - 以特定方式对 vector 中的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65178460/

相关文章:

c++ - 在 C++ 中,如何在运行时获取给定元素的模板类型?

C++:尝试在二进制到十进制转换器中多次将非常大的整数加在一起,而您的输入是字符串值

java - 将 url 加载到字符串变量

linux - 就地排序文件

Java - 在已经排序的列表上调用 sort() 是 O(1) 操作吗?

c - 在 C 中重新排列交替正负的数组

java - Collections.Sort() 的行为;

c++ - 有没有办法从此 sql 语句和逻辑中删除 select count(*)

c++ - 函数重载和模板

c# - 带有转义字符的字符串格式