C ++散列具有许多属性的自定义对象

时间:2016-11-30 06:56:00

标签: c++ hash

所以我按照这篇文章中的过程来使用具有多个属性的自定义对象进行哈希:C++ unordered_map using a custom class type as the key

我不认为我这样做是正确的。代码运行,但它没有散列到正确的位置。

struct Merged_Group {
    string cid, building, room, time, day, subj, crse, major, status, level, sid;

    bool operator==(const Merged_Group &other) const
    {
        return ((cid == other.cid) ||

                (subj != other.subj &&
                crse != other.crse &&
                room == other.room &&
                time == other.time &&
                day == other.day &&
                building == other.building) ||

                sid == other.sid &&
                (major != other.major ||
                status != other.status ||
                level != other.level ));
    }
};

布尔运算符在检查我正在寻找的条件方面是正确的,但是我的哈希方式似乎是不正确的。 (老实说,我盲目地写了这篇文章而没有完全理解它是如何工作的,我只是引用了帖子......所以请耐心等待。)

namespace std {

    template <>
    struct hash<Merged_Group>
    {
        std::size_t operator()(const Merged_Group& k) const
        {

            return ((hash<string>()(k.cid) 
                ^ (hash<string>()(k.subj) << 1)
                ^ (hash<string>()(k.crse) << 1)
                ^ (hash<string>()(k.room) << 1)
                ^ (hash<string>()(k.time) << 1)
                ^ (hash<string>()(k.day) << 1)
                ^ (hash<string>()(k.building) << 1)
                ^ (hash<string>()(k.sid) << 1)
                ^ (hash<string>()(k.major) << 1)
                ^ (hash<string>()(k.status) << 1)) >> 1)
                ^ (hash<string>()(k.level) << 1);
        }
    };

}

任何建议表示赞赏。

0 个答案:

没有答案