What is the best way to use a HashMap in C++?

前端 未结 5 1714
死守一世寂寞
死守一世寂寞 2020-12-02 03:48

I know that STL has a HashMap API, but I cannot find any good and thorough documentation with good examples regarding this.

Any good examples will be appreciated.

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 04:21

    Evidence that std::unordered_map uses a hash map in GCC stdlibc++ 6.4

    This was mentioned at: https://stackoverflow.com/a/3578247/895245 but in the following answer: What data structure is inside std::map in C++? I have given further evidence of such for the GCC stdlibc++ 6.4 implementation by:

    • GDB step debugging into the class
    • performance characteristic analysis

    Here is a preview of the performance characteristic graph described in that answer:

    How to use a custom class and hash function with unordered_map

    This answer nails it: C++ unordered_map using a custom class type as the key

    Excerpt: equality:

    struct Key
    {
      std::string first;
      std::string second;
      int         third;
    
      bool operator==(const Key &other) const
      { return (first == other.first
                && second == other.second
                && third == other.third);
      }
    };
    

    Hash function:

    namespace std {
    
      template <>
      struct hash
      {
        std::size_t operator()(const Key& k) const
        {
          using std::size_t;
          using std::hash;
          using std::string;
    
          // Compute individual hash values for first,
          // second and third and combine them using XOR
          // and bit shifting:
    
          return ((hash()(k.first)
                   ^ (hash()(k.second) << 1)) >> 1)
                   ^ (hash()(k.third) << 1);
        }
      };
    
    }
    

提交回复
热议问题