c++ - 重新定义 < 运算符以在字符串的 STL 算法中使用

标签 c++ templates operator-overloading std

是否可以重新定义operator <对于不修改 std 命名空间的字符串,让这个运算符在标准算法中使用? 例如,我可以这样写:

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 <将被使用并且不会打印任何内容。是否可以制作std::sort使用自定义 operator <不将其包含到 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 */ });

关于c++ - 重新定义 < 运算符以在字符串的 STL 算法中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44390785/

相关文章:

c++ - 如何在 Visual C++ 中使用#pragma 同时启用两个语言环境?

c++ - IDE (CLion) 无法解析 C++ 模板类型

javascript - Javascript 中数组的重载 [] 运算符

c++ - 运算符==比较两个不同的类

c++ - 如何对类的 const 实例使用打印运算符?

c++ - 解释来自 cppreference.com 的关于迭代器标签的示例代码

c++ - 未定义对析构函数的引用

C++ 不可重载函数

c++ - 如何防止 C++ 模板的特化?

c++ - 如何返回模板类中成员变量的拷贝?