Skip to content

Instantly share code, notes, and snippets.

@AggamR
Created July 23, 2021 11:23
Show Gist options
  • Save AggamR/980290ead1d568cee4692c200d9cc58d to your computer and use it in GitHub Desktop.
Save AggamR/980290ead1d568cee4692c200d9cc58d to your computer and use it in GitHub Desktop.
a simple include for hash tables in c++
#include <string>
#define CAPACITY 100
// copied from the internet (thanks internet)
unsigned long hash_function(std::string str) {
unsigned long i = 0;
for (int j=0; j < str.length(); j++)
i += str.at(j);
return i % CAPACITY;
}
typedef struct hash_table
{
unsigned int keys[CAPACITY];
std::string values[CAPACITY];
unsigned int counter;
void append(std::string key, std::string value) {
if (counter+1 > CAPACITY) return;
keys[counter] = hash_function(key);
values[counter] = value;
counter++;
}
std::string get(std::string key) {
int keyIndex = -1;
for (int i = 0; i < counter; i++) {
if (hash_function(key) == keys[i]) {
keyIndex = i;
break;
}
}
if (keyIndex == -1) return "";
return values[keyIndex];
}
} hash_table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment