Simple hashmap implementation in C++

后端 未结 5 1868
别那么骄傲
别那么骄傲 2020-12-08 00:50

I\'m relatively new to C++. In Java, it\'s easy for me to instantiate and use a hashmap. I\'d like to know how to do it in a simple way in C++, since I saw many different im

相关标签:
5条回答
  • 2020-12-08 01:24

    Most compilers should define std::hash_map for you; in the coming C++0x standard, it will be part of the standard library as std::unordered_map. The STL Page on it is fairly standard. If you use Visual Studio, Microsoft has a page on it.

    If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like int, char, bool and even char *) should "just work" as keys in a hash_map. However, for anything else you will have to define your own hashing and equality functions and then write "functors" that wrap them in a class.

    Assuming your class is called MyClass and you have already defined:

    size_t MyClass::HashValue() const { /* something */ }
    bool MyClass::Equals(const MyClass& other) const { /* something */ }
    

    You will need to define two functors to wrap those methods in objects.

    struct MyClassHash {
      size_t operator()(const MyClass& p) const {
        return p.HashValue();
      }
    };
    
    struct MyClassEqual {
      bool operator()(const MyClass& c1, const MyClass& c2) const {
        return c1.Equals(c2);
      }
    };
    

    And instantiate your hash_map/hash_set as:

    hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map;
    hash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set;
    

    Everything should work as expected after that.

    0 讨论(0)
  • 2020-12-08 01:26

    Check out Simple Hash Map (Hash Table) Implementation in C++ for a basic Hash Table with generic type key-value pairs and separate chaining strategy.

    0 讨论(0)
  • 2020-12-08 01:31

    Using hashmaps in C++ is easy! It's like using standard C++ map. You can use your's compiler/library implementation of unordered_map or use the one provided by boost, or some other vendor. Here's a quick sample. You will find more if you follow the links you were given.

    #include <unordered_map>
    #include <string>
    #include <iostream>
    
    int main()
    {
        typedef std::tr1::unordered_map< std::string, int > hashmap;
        hashmap numbers;
    
        numbers["one"] = 1;
        numbers["two"] = 2;
        numbers["three"] = 3;
    
        std::tr1::hash< std::string > hashfunc = numbers.hash_function();
        for( hashmap::const_iterator i = numbers.begin(), e = numbers.end() ; i != e ; ++i ) {
            std::cout << i->first << " -> " << i->second << " (hash = " << hashfunc( i->first ) << ")" << std::endl;
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-08 01:33

    Take a look at boost.unordered, and its data structure.

    0 讨论(0)
  • 2020-12-08 01:33

    Try boost's unordered classes.

    0 讨论(0)
提交回复
热议问题