c++ - 有什么可以一般地反转 C++ Comparator 类型吗?

标签 c++ templates comparator c++-standard-library

例如,如果我传入 std::less ,我希望它创建一个行为等于 std::greater 的新比较器.用于模板。

可以启用类似 std::map<int, int, std::invert<std::less>> 的语法的东西(除非我要找的东西存在,那不是它的名字)。这存在吗?

最佳答案

std::not_fnwhich :

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/

相关文章:

java - 在 Java 8 中使用流式链接对集合进行排序

c++ - 一种为特定内联函数强制汇编列表的方法,更好的方法?

c++ - int&& 和 template<class T> T&& 的区别

c++ - 无法在 ROS 中使用本地安装的 Protocol Buffers

html - AngularDart - 使用表单操作

c++ - 两种模板代码模式之间的差异,一种情况下分配了数字,而另一种情况下使用关键字 typename

java - 在java中实现比较器接口(interface)

Angularjs orderBy : how to call default comparator from custom sort function

c++ - 为什么对 isnan 的调用没有歧义? a.k.a. 使用引入 2 次相似函数声明的关键字

c++ - 链接 libboost_log.so 使 boost::asio::io_service::run 立即退出