C++ unordered_map fail when used with a vector as key

后端 未结 2 739
太阳男子
太阳男子 2020-12-05 05:03

Background: I am comming from the Java world and I am fairly new to C++ or Qt.

In order to play with unordered_map, I have written the following simple program:

<
2条回答
  •  伪装坚强ぢ
    2020-12-05 05:58

    I found R. Martinho Fernandes's answer unsuitable for competitive programming since most of the times you have to deal with a provided IDE and cannot use an external library such as boost. You can use the following method if you'd like to make the best of STL.

    As already stated above, you just need to write a hash function. And it should specialize for the kind of data stored in your vector. The following hash function assumes int type data:

    struct VectorHasher {
        int operator()(const vector &V) const {
            int hash = V.size();
            for(auto &i : V) {
                hash ^= i + 0x9e3779b9 + (hash << 6) + (hash >> 2);
            }
            return hash;
        }
    };
    

    Note that you can use any kind of operation to generate a hash. You just need to be creative so that collisions are minimized. For example, hash^=V[i], hash|=V[i], hash+=V[i]*V[i] or even hash+=(V[i]< are all valid until of course, your hash doesn't overflows.

    Finally to use this hash function with your unordered_map, initialize it as follows:

    unordered_map,string,VectorHasher> hashMap;
    

提交回复
热议问题