【问题标题】:Qt: how to implement a hash function for QColor?Qt:如何为 QColor 实现哈希函数?
【发布时间】:2022-01-07 12:12:56
【问题描述】:

我需要使用std::pair<QColor, char> 作为unordered_map 的键。至于pair,我知道有boost功能可以使用,但是颜色呢?仅在 std 命名空间中提供哈希模板就足够了吗?如果是这样,作为散列基础的颜色的最佳属性是什么,以最大限度地提高性能并最大限度地减少冲突?我的第一个想法是简单的name()。如果是这样

namespace std {
    struct hash<Key>
    {
        std::size_t operator()(const Key& k) const {
            return std::hash<std::string>()(k.name());
    }
}

以上代码取自C++ unordered_map using a custom class type as the key

【问题讨论】:

    标签: c++ qt hash c++14


    【解决方案1】:

    您的建议可能会起作用(尽管您必须将颜色名称从 QString 转换为 std::string),我会直接使用颜色的 RGBA 值。这比必须经过QStringstd::string 的构造和哈希计算要便宜一些:

    template<>
    struct std::hash<QColor>
    {
      std::size_t operator()(const QColor& c) const noexcept
      {
        return std::hash<unsigned int>{}(c.rgba());
      }
    };
    

    根据 Qt 的文档,QColor::rgba() 返回的QRgb 是与unsigned int 等效的某种类型。

    【讨论】:

    • 一个问题:在哪里定义 std::hash 的扩展更好?在一个单独的标题中,然后只包含它或只是一些源文件?
    • 视情况而定,如果您只需要在一个 .cpp 文件(翻译单元)中使用此哈希功能,则可以将其放入该文件中,否则将其放入标题中。
    猜你喜欢
    • 2016-03-25
    • 2015-07-06
    • 2011-01-19
    • 2021-04-06
    • 2010-09-06
    • 2022-12-04
    • 2015-02-02
    • 2016-03-05
    • 2011-10-11
    相关资源
    最近更新 更多