重新定义 < 运算符以在字符串的 stl 算法中使用

redefine < operator to use in stl algorithms for strings

是否可以在不修改 std 命名空间的情况下为字符串重新定义 operator <,以使该运算符在标准算法中使用? 例如,我可以写:

namespace std
{

    bool operator <(const std::string & rhs, const std::string & lhs)
    {
        std::cout << "lol";
        return false;
    }

}

int main()
{
    std::vector<std::string> lol = { "a", "b", "ba", "aa" };
    std::sort(lol.begin(), lol.end());
}

和"lol"会打印多次。但是,如果我将 operator < 移出 std 命名空间,将使用默认值 operator < 并且不会打印任何内容。是否可以使用自定义 operator < 来制作 std::sort 而无需将其包含在 std 命名空间中?

是的,我知道,我可以将另一个比较器传递给 std::sort,但如果我能按照我的要求做,以及如何做,这对我来说很有趣?

另外我是对的,将这样的模板特化添加到 std 命名空间是正确的吗?

更新:这不是实际问题,我只是想知道如果可能的话我该怎么做。

不,不是。将函数添加到标准命名空间是未定义的行为。 [namespace.std]/1 状态:

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

如果您想更改 std::sort 排序方式,那么您可以提供一个 lambda 并定义您想要的内容

std::sort(std::begin(foo), std::end(foo), [](const auto& lhs, const auto& rhs) { /* your code here */ });

Is it possible to redefine operator < for strings without modifiying std namespace

当然,您可以在另一个命名空间中定义重载。但是正如您所发现的,除非明确限定,否则重载决议不会找到它。

Is it possible to make std::sort using custom operator < without including it to std namespace?

是的,你似乎已经知道怎么做了:

Yes I know, I can pass another comparator to std::sort

这正是比较器参数的用途。

Also am I correct, that it's corect to add such template specialization to std namespace?

这不是模板专业化;它是一个函数定义,您不能将函数定义添加到 std 命名空间 - 否则行为是未定义的。您将被允许添加模板特化,但前提是至少一个类型参数是用户定义的类型。