fork download
  1. #include<iostream>
  2. using namespace std;
  3. class HashEntry {
  4. public:
  5. int key;
  6. int value;
  7. HashEntry(int key, int value) {
  8. this->key=key;
  9. this->value=value;
  10. }
  11. };
  12. class HashMap {
  13. private:
  14. HashEntry **table;
  15. int capacity;
  16. int mod;
  17. int hashFunc(int key) {
  18. return key%mod;
  19. }
  20. public:
  21. HashMap(int capacity, int mod) {
  22. this->capacity=capacity;
  23. this->mod=mod;
  24. table=new HashEntry*[capacity];
  25. for(int i=0; i<capacity; i++)
  26. table[i]=nullptr;
  27. }
  28. // Destructor to clean up allocated memory
  29. ~HashMap() {
  30. for(int i=0; i<capacity; i++)
  31. if (table[i]!=nullptr)
  32. delete table[i];
  33. delete[] table;
  34. }
  35. // Function to insert a key-value pair into the hash table
  36. void insert(int key, int value) {
  37. int hash=hashFunc(key);
  38. int startHash=hash;
  39. while (table[hash]!=nullptr && table[hash]->key!=key) {
  40. hash=(hash+1)%capacity;
  41. if(hash==startHash) {
  42. return;
  43. }
  44. }
  45. if(table[hash]!=nullptr) {
  46. delete table[hash];
  47. }
  48. table[hash]=new HashEntry(key, value);
  49. }
  50. // Function to search for a key and return its value
  51. int search(int key) {
  52. int hash=hashFunc(key);
  53. int startHash=hash;
  54. while(table[hash]!=nullptr && table[hash]->key!=key) {
  55. hash=(hash+1)%capacity;
  56. if(hash==startHash) {
  57. return -1;
  58. }
  59. }
  60. if (table[hash]==nullptr) {
  61. return -1;
  62. }
  63. else {
  64. return table[hash]->value;
  65. }
  66. }
  67. void printTable() {
  68. cout<<"Hash Table:"<<endl;
  69. for(int i=0; i<capacity; i++) {
  70. if (table[i]!=nullptr)
  71. cout<<i<<" => Key: "<<table[i]->key<<", Value: "<<table[i]->value<<endl;
  72. else
  73. cout<<i<<" => null"<<endl;
  74. }
  75. }
  76. };
  77. int main() {
  78. HashMap hash(10,7);
  79. hash.insert(1,10);
  80. hash.insert(8,50);
  81. hash.insert(15,90);
  82. cout<<"Value at key 1: "<<hash.search(1)<<endl;
  83. cout<<"Value at key 8: "<<hash.search(8)<<endl;
  84. cout<<"Value at key 15: "<<hash.search(15)<<endl;
  85. cout<<"Value at key 2: "<<hash.search(2)<<endl;
  86. hash.printTable();
  87. return 0;
  88. }
  89.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
Value at key 1: 10
Value at key 8: 50
Value at key 15: 90
Value at key 2: -1
Hash Table:
0 => null
1 => Key: 1, Value: 10
2 => Key: 8, Value: 50
3 => Key: 15, Value: 90
4 => null
5 => null
6 => null
7 => null
8 => null
9 => null