美文网首页
Design a HashMap class in C++. I

Design a HashMap class in C++. I

作者: SilentSummer | 来源:发表于2017-12-23 13:32 被阅读12次

要实现的HashMap结构如图:


82011513790380_.pic_hd.jpg

Code:

// Compiled with: g++ -Wall -std=c++14 -pthread

#include <iostream>
#include <string>

using namespace std;

class HashMap {
    typedef struct entry {
        unsigned int key;
        string value;
        entry* next;
        unsigned int hash;
    } entry;
    
    entry* Bucket[16] = {nullptr};
    
  public:
    void Put(const unsigned int key, const string& value) {
        unsigned int ind = key%16;
        entry* i;
        for (i = Bucket[ind]; i != nullptr; i = i->next) {
            if (i->key == key) {
                i->value = value;
                break;
            }
        }

        if (i == nullptr) {
            entry *node = new entry(); 
            node->key = key;
            node->value = value;
            node->next = Bucket[ind];
            node->hash = ind;
            Bucket[ind] = node;    
        }
    }
    
    entry* Get(const unsigned key) {
        unsigned int ind = key%16;
        entry* i;
        for (i = Bucket[ind]; i != nullptr; i = i->next) {
            if (i->key == key) {
                break;
            }
        }
        
        if (i != nullptr) {
            return i;
        }
        else {
            return nullptr;
        }
    }
};

int main(){
    HashMap hashmap;
    
    hashmap.Put(0, "hello");
    hashmap.Put(1, "HELLO");
    hashmap.Put(18, "hEllo18");
    hashmap.Put(16, "hello16");
    hashmap.Put(17, "world");
    
    unsigned int testkey = 0;
    if (!hashmap.Get(testkey)) {
        cout << "no found" << endl;
    }
    else {
        cout << hashmap.Get(testkey)->value << endl;
    }
    
    cout << "Hello, World!" << endl;
    return 0;
}

相关文章

网友评论

      本文标题:Design a HashMap class in C++. I

      本文链接:https://www.haomeiwen.com/subject/zyfqgxtx.html