是否可以重新定义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/