Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- template <class TypeValue>
- class HashEntry {
- public:
- HashEntry(int key, TypeValue value) {
- this->key = key;
- this->value = value;
- }
- int getKey() {
- return key;
- }
- TypeValue getValue() {
- return value;
- }
- private:
- int key;
- TypeValue value;
- };
- const int TABLE_SIZE = 128;
- template <class TypeValue>
- class HashMap {
- private:
- HashEntry<TypeValue> **table;
- public:
- HashMap() {
- table = new HashEntry<TypeValue> *[TABLE_SIZE];
- for (int i = 0; i < TABLE_SIZE; i++)
- table[i] = NULL;
- }
- TypeValue get(int key) {
- int hash = (key % TABLE_SIZE);
- while (table[hash] != NULL && table[hash]->getKey() != key)
- hash = (hash + 1) % TABLE_SIZE;
- if (table[hash] == NULL)
- return TypeValue();
- else
- return table[hash]->getValue();
- }
- void put(int key, TypeValue value) {
- int hash = (key % TABLE_SIZE);
- while (table[hash] != NULL && table[hash]->getKey() != key)
- hash = (hash + 1) % TABLE_SIZE;
- if (table[hash] != NULL)
- delete table[hash];
- table[hash] = new HashEntry<TypeValue>(key, value);
- }
- ~HashMap() {
- for (int i = 0; i < TABLE_SIZE; i++)
- if (table[i] != NULL)
- delete table[i];
- delete[] table;
- }
- };
- using namespace std;
- int main()
- {
- //considerando un TABLE_SIZE = 128
- HashMap<string> h;
- h.put(4,"Jorge");
- h.put(3,"Samuel");
- h.put(6,"Tomas");
- h.put(1,"Lucas");
- h.put(1000,"Benjamin");
- h.put(1124,"Felipe");
- h.put(13451,"Cristobal");
- h.put(21,"David");
- cout << endl <<"key(4):\t\tvalue="<<h.get(4);
- cout << endl <<"key(6):\t\tvalue="<<h.get(6);
- cout << endl <<"key(1):\t\tvalue="<<h.get(1);
- cout << endl <<"key(1000):\tvalue="<<h.get(1000);
- cout << endl <<"key(1124):\tvalue="<<h.get(1124);
- cout << endl <<"key(13451):\tvalue="<<h.get(13451);
- cout << endl <<"key(21):\tvalue="<<h.get(21);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement