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

前端 未结 5 1721
死守一世寂寞
死守一世寂寞 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条回答
  •  猫巷女王i
    2020-12-02 04:15

    For those of us trying to figure out how to hash our own classes whilst still using the standard template, there is a simple solution:

    1. In your class you need to define an equality operator overload ==. If you don't know how to do this, GeeksforGeeks has a great tutorial https://www.geeksforgeeks.org/operator-overloading-c/

    2. Under the standard namespace, declare a template struct called hash with your classname as the type (see below). I found a great blogpost that also shows an example of calculating hashes using XOR and bitshifting, but that's outside the scope of this question, but it also includes detailed instructions on how to accomplish using hash functions as well https://prateekvjoshi.com/2014/06/05/using-hash-function-in-c-for-user-defined-classes/

    namespace std {
    
      template<>
      struct hash {
        size_t operator()(const my_type& k) {
          // Do your hash function here
          ...
        }
      };
    
    }
    
    1. So then to implement a hashtable using your new hash function, you just have to create a std::map or std::unordered_map just like you would normally do and use my_type as the key, the standard library will automatically use the hash function you defined before (in step 2) to hash your keys.
    #include 
    
    int main() {
      std::unordered_map my_map;
    }
    

提交回复
热议问题