c++ - 为什么 C++ 关联容器谓词默认不透明?

标签 c++ containers predicate associative

从 C++14 开始我们有 std::less<void>在大多数情况下这是透明且更有用的,所以有理由,例如,std::set还有std::less<Key>默认情况下作为谓词,而不是 std::less<void>历史原因除外。

用例:std::set<std::string>::findstd::string_view

最佳答案

这样做会破坏当前的工作代码。想象一下我有

struct my_type
{
    int id;
    int bar;
};

namespace std {
    template<>
    struct less<my_type>
    {
        bool operator()(my_type const& lhs, my_type const& rhs)
        {
            return lhs.id < rhs.id; // bar doesn't need to be compared, only need unique id's in the container.
        }
    };
}

std::set<my_type> foo;

如果std::set已更改为使用 std::less<void>那么这段代码将不再编译,因为 my_type没有 operator < .

关于c++ - 为什么 C++ 关联容器谓词默认不透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54135237/

相关文章:

C++如何在删除上一行后使用同一行打印文本?

mysql - Drupal 环境的 Docker 容器未链接

java - 如何知道屏幕上容器或窗口的确切大小?

ios - Swift - 分组和排序列表项

c++ - Makefile C++继承

c++ - 向 Windows 10 应用程序发送 BM_CLICK 消息不起作用

c++ - auto using parens 可以表示函数原型(prototype)吗?

hadoop - 验证 Cloudera Hadoop 服务是否在容器中运行

haskell - 在 IO 中处理谓词的惯用 Haskell 方式是什么?

prolog - 有人可以逐步描述这个 Prolog 代码吗?