Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <iostream>
- #include <stdlib.h>
- #include <time.h>
- using namespace std;
- class HashEntry {
- private:
- int key;
- int value;
- public:
- HashEntry(int key, int value) {
- this->key = key;
- this->value = value;
- }
- int getKey() {
- return key;
- }
- int getValue() {
- return value;
- }
- void delEl(){
- delete this;
- }
- };
- const int TABLE_SIZE = 50;
- class HashMap {
- private:
- HashEntry **table;
- public:
- HashMap() {
- table = new HashEntry*[TABLE_SIZE];
- for (int i = 0; i < TABLE_SIZE; i++)
- table[i] = NULL;
- }
- int 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 && table[hash]->getValue() != 0 )
- return table[hash]->getValue();
- }
- void del_el(int key) {
- int hash = (key % TABLE_SIZE);
- if (table[hash]->getValue() % 2 == 0 ) {
- table[hash]=NULL;
- table[hash]->delEl();
- }
- }
- void put(int key, int 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(key, value);
- }
- /* ~HashMap() {
- for (int i = 0; i < TABLE_SIZE; i++)
- if (table[i] != NULL)
- delete table[i];
- delete[] table;
- }*/
- };
- int main () {
- srand(time(NULL));
- HashMap a;
- for (int i=0;i<TABLE_SIZE;i++)
- a.put(i,rand()%20+1);
- int c;
- cout << "Generated Hash table:" << endl;
- for (int i=0;i<TABLE_SIZE;i++) {
- c = a.get(i);
- cout << c << " ";
- }
- cout << endl << "Hash table after deleting even elements:" << endl;
- for (int i=0;i<TABLE_SIZE;i++)
- a.del_el(i);
- for (int i=0;i<TABLE_SIZE;i++) {
- c=a.get(i);
- cout << c << " ";
- }
- cout << endl << endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement