I wanted to create a hash table that contains strings separated by their initial characters. There are 26 vectors in my hash table for 26 letters.
#ifndef _MYHASHTABLE_H_
#define _MYHASHTABLE_H_
#include <string>
#include <vector>
class myHashTable {
private:
int n;
std::vector<int> intMyVector[26];
std::vector<std::string> strMyVector[26];
public:
int hashFunction(std::string str);
void pushBack(std::string str, int i);
void display();
};
#endif
#include "myHashTable.h"
#include <iostream>
#include <string>
int myHashTable::hashFunction(std::string str) {
if (*str.begin() <= 122 && *str.begin() >= 97)
return (*str.begin() % 26) - 19;
else if (*str.begin() <= 90 && *str.begin() >= 65)
return (*str.begin() % 26) - 13;
}
void myHashTable::pushBack(std::string str, int i) {
strMyVector[hashFunction(str)].push_back(str);
intMyVector[hashFunction(str)].push_back(i);
}
void myHashTable::display() {
for (int i{}; i < 26; i++) {
for (int j{}; j < (strMyVector[i].size()); j++)
std::cout << strMyVector[i][j] << " " << intMyVector[i][j] << std::endl;
}
}
First I give 3 inputs with "a", "b", "c" initials. There was not any error. But whenever I break the alphabetical order it crashes and it doesn't even display the first 3 outputs. How do I fix this problem?
#include <iostream>
#include <string>
#include <vector>
#include "myHashTable.h"
int main() {
myHashTable hash;
hash.pushBack("abcd", 1);
hash.pushBack("bcd", 2);
hash.pushBack("cda", 4);
hash.pushBack("zaxs", 1);
hash.display();
return 0;
}