例如,如果我传入 std::less
,我希望它创建一个行为等于 std::greater
的新比较器.用于模板。
可以启用类似 std::map<int, int, std::invert<std::less>>
的语法的东西(除非我要找的东西存在,那不是它的名字)。这存在吗?
最佳答案
有std::not_fn
,which :
Creates a forwarding call wrapper that returns the negation of the callable object it holds.
但是,在这种情况下,它会导致比较器具有 std::greater_equal
的功能,而不是 std::greater
的功能。此外,该类型与 std::greater_equal
不同。
例子:
auto greater_eq = std::not_fn(std::less<>());
要获得 std::greater
的等价物,您可以通过翻转参数来获得它。我不认为标准库中有这样的函数,但自己编写很简单:
auto flip = [](auto fun) {
return [fun = std::move(fun)]
(const auto& arg1, const auto& arg2)
{
return fun(arg2, arg1);
};
};
auto greater = flip(std::less<>());
这也可以扩展为支持任意数量的参数,仅翻转前两个(使其类似于 Haskell 中的 flip
),以及支持参数的完美转发,但那些功能可能会使简洁的示例变得相当复杂,并且不需要比较器。
关于c++ - 有什么可以一般地反转 C++ Comparator 类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56387837/