使用std :: sort对字符串进行排序,以便大写字母位于小写字母之后

Mar*_*ars 6 c++ sorting string

我想对矢量进行排序,以便大写字母遵循小写字母.如果我有类似的东西

This is a test
this is a test
Cats
cats
this thing
Run Code Online (Sandbox Code Playgroud)

我希望输出

cats
Cats
this is a test
This is a test
this thing
Run Code Online (Sandbox Code Playgroud)

将输出标准库排序

Cats
This is a test
cats
this is a test
this thing
Run Code Online (Sandbox Code Playgroud)

我想将一个谓词传递给std :: sort,以便它比较我作为参数传递的字符串的小写版本.

bool compare(std::string x, std::string y)
{
    return lowercase(x) < lowercase(y);
}
Run Code Online (Sandbox Code Playgroud)

我尝试降低函数中的每个字符,然后进行比较,但它不起作用.我想通过一些其他方法将字符串转换为小写来测试这种方法.如何将字符串转换为小写?

编辑::

其实我找出了问题所在.这有效.当我第一次写的功能,而不是ref = tolower(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;
}
Run Code Online (Sandbox Code Playgroud)

编辑::

这个代码实际上有时首先用大写字母排序,而其他时候用大写字母排序第二,所以它不能完全解决问题.

Ben*_*ley 1

您的解决方案几乎已经完成,您只需要在字符串的小写版本相等的情况下进行特殊处理:

std::string to_lower(std::string s)
{
    for (auto & c : s)
        c = std::tolower(c);
    return s;
}

bool string_comp(std::string const & lhs, std::string const & rhs)
{

    auto lhs_lower = to_lower(lhs);
    auto rhs_lower = to_lower(rhs);
    if (lhs_lower == rhs_lower)
        return rhs < lhs;
    return lhs_lower < rhs_lower;
}
Run Code Online (Sandbox Code Playgroud)

这可能需要一些优化。不需要复制字符串。当然,您可以就地进行不区分大小写的比较。但该功能在标准库中并不方便使用,因此我将这个练习留给您。