Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
- using namespace std;
- // Declare the struct
- #define EMPTY_STUDENT_ID 0 // An Id of 0 means an empty record.
- struct Student
- {
- int id;
- std::string name;
- std::string telephone;
- std::string email;
- Student* pNext;
- };
- /*
- The HashTable is a structure of 2 elements, the first element records the size of the prime area
- and the second element is a pointer to the start of the prime area.
- */
- struct HashTable
- {
- int size; /* the size of the table */
- Student *primeArea; /* the table elements */
- };
- HashTable *my_hash_table;
- int size_of_table = 12;
- // Create an array of students.
- // These will be put into a hash table
- Student studentList[] =
- {
- {379452, "Mary Odd", "5555555", "mary@gmail.com" },
- {367173, "Sarah Alice", "5555555", "sarah@gmail.com" },
- {166702, "Harry Joy", "5555555", "harry@gmail.com" },
- {572556, "Hidayah", "5555555", "harry@gmail.com"},
- };
- HashTable* create_hash_table(int size)
- {
- HashTable* new_table;
- if (size<1) return NULL; /* invalid size for table */
- // Allocate the hash table main structure
- if ((new_table = new HashTable) == NULL) {
- return NULL;
- }
- // Allocate the primeArea
- if ((new_table->primeArea = new Student[size]) == NULL) {
- return NULL;
- }
- /* Initialize the elements of the table */
- for(int i=0; i<size; i++)
- {
- new_table->primeArea[i].pNext = NULL;
- // An id of 0 means an empty record.
- new_table->primeArea[i].id = EMPTY_STUDENT_ID;
- }
- /* Set the table's size */
- new_table->size = size;
- return new_table;
- }
- // This is a hashing function.
- unsigned int moduloDivisionHashFunction(Student *pStudent, unsigned int listSize)
- {
- return pStudent->id % listSize;
- }
- void insert_to_hash_table(HashTable* ht, Student* record)
- {
- //This is where the chaining solution should be taken
- unsigned int hashValue = moduloDivisionHashFunction(record, my_hash_table->size);
- cout<< "Student ID " << record->id << " hashes to " << hashValue << endl;
- ht->primeArea[hashValue].id = record->id;
- ht->primeArea[hashValue].name = record->name;
- ht->primeArea[hashValue].telephone= record->telephone;
- ht->primeArea[hashValue].email = record->email;
- }
- int main(void)
- {
- cout<<"Modulo-Division Hashing Function"<<endl;
- my_hash_table = create_hash_table(size_of_table);
- // go through the studentList using a loop
- int studentListSize = ARRAY_SIZE(studentList);
- for(int i = 0; i < studentListSize ; i++)
- {
- insert_to_hash_table(my_hash_table, &studentList[i]);
- }
- system("pause");
- return 0;
- }
Add Comment
Please, Sign In to add comment