0

So I followed the procedure from this post to hash by custom objects with multiple attributes: C++ unordered_map using a custom class type as the key

I don't think I am doing this properly. The code runs, but it is not hashing to the correct location.

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 ));
    }
};

The boolean operator is correct in the sense of checking the conditions I am looking for, however the way I am hashing seems to be incorrect. (To be honest, I wrote this blindly without completely understanding how it works, I just referenced the post... so bear with me).

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);
        }
    };

}

Any advice is appreciated.

Community
  • 1
  • 1
onesiumus
  • 279
  • 6
  • 26
  • [std::hash](http://en.cppreference.com/w/cpp/utility/hash): For two parameters k1 and k2 that are equal, `std::hash()(k1) == std::hash()(k2).` Its not the case for your code, you may have two very different objects look equal (==) but hashed to different value – Oleg Bogdanov Nov 30 '16 at 07:11
  • 2
    You're == doesn't create equivalence classes. That is you can have A==B , A==C but C!=B. Suppose they all share room, day , time , building but B & C are the same subject and course but A isn't and that none share a sid or cid. I don't know if that's a valid state but those != in the == operator can cause anomalies. – Persixty Nov 30 '16 at 07:18

0 Answers0