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

前端 未结 5 1713
死守一世寂寞
死守一世寂寞 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:29

    Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:

    #include 
    #include 
    
    class Hashtable {
        std::unordered_map htmap;
    
    public:
        void put(const void *key, const void *value) {
                htmap[key] = value;
        }
    
        const void *get(const void *key) {
                return htmap[key];
        }
    
    };
    
    int main() {
        Hashtable ht;
        ht.put("Bob", "Dylan");
        int one = 1;
        ht.put("one", &one);
        std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
    }
    

    Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)

提交回复
热议问题