【发布时间】:2013-10-22 04:41:56
【问题描述】:
我想对向量进行排序,使大写字母跟在小写字母之后。如果我有类似的东西
This is a test
this is a test
Cats
cats
this thing
我希望输出是
cats
Cats
this is a test
This is a test
this thing
标准库排序会输出
Cats
This is a test
cats
this is a test
this thing
我想向 std::sort 传递一个谓词,以便它比较我作为参数传递的字符串的小写版本。
bool compare(std::string x, std::string y)
{
return lowercase(x) < lowercase(y);
}
我尝试降低函数中的每个字符,然后进行比较,但没有奏效。我想通过其他方法将字符串转换为小写来测试这种方法。如何将字符串转换为小写?
编辑::
其实我发现了问题所在。这行得通。当我第一次编写函数时,我有 tolower(ref) 而不是 ref = tolower(ref) 没有重新分配给 ref 所以它什么也没做。
bool compare(std::string x, std::string y)
{
for(auto &ref:x)
ref = tolower(ref);
for(auto &ref:y)
ref = tolower(ref);
return x < y;
}
编辑::
此代码实际上有时会先排序大写字母,有时会先排序大写字母,因此并不能完全解决问题。
【问题讨论】:
-
我想您可以使用
std::mismatch来查找第一个不匹配的字符,然后使用std::islower和std::tolower确定哪个更少。 -
不过,这不会按照您想要的方式进行排序。它将不分青红皂白地对大小写进行排序。最简单的解决方案可能是使用具有您想要的顺序的区域设置排序,例如:
std::sort(v.begin(), v.end(), std::locale("en_US.UTF-8"));(您需要#include <locale>) -
我认为你的更新会给你 Cat,cats,This is a test,this is a test,this thing See here
-
@P0W。是的,我去测试了几个不同的字符串,它按字母顺序排序,但大写字母有时在前面,有时在后面。
-
@Dochevsky:这是因为您刚刚告诉
std::sort,小写和大写字母是相同的,因此第一个或第二个并不重要:) 我有一个关于你的例子,奇怪的是"this""This" "this"(整圈!),所以我想知道你是否打算进行依赖于任意数量的字符/单词的比较,或者如果你只希望T在t之后到达,在这种情况下,顺序应该是cats, Cats, this is a test, this thing, This is a test。