Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef LR5FORKIRILL_HASHTABLE_H
- #define LR5FORKIRILL_HASHTABLE_H
- #include <vector>
- #include <string>
- using namespace std;
- namespace hashTable {
- template<class Elem1, class Elem2>
- class Table {
- private:
- struct node {
- Elem1 key;
- Elem2 value;
- node() {
- this->key = "";
- this->value = "";
- }
- node(Elem1 key, Elem2 value) {
- this->key = key;
- this->value = value;
- }
- bool isEmpty() {
- return key == "" && value == "";
- }
- };
- int tableSize;
- int initialSize;
- vector<node> hashTable;
- int hashFunc(const string &key) { //хэш-функция
- int hashCode = 0;
- for (char i : key) { //считаем сумму аски кодов символов ключа
- hashCode += (int) i;
- }
- //return 3;
- return hashCode % initialSize; //берем остаток от размера массива
- }
- public:
- Table(int size = 100) {
- tableSize = size;
- initialSize = size;
- hashTable = vector<node>(size);
- }
- void printTable() {
- for (int i = 0; i < tableSize; i++) {
- if(!(hashTable.at(i)).isEmpty())
- cout << i << " "<< (hashTable.at(i)).key << " " << (hashTable.at(i)).value << endl;
- }
- }
- void insert(Elem1 key, Elem2 value){
- int index = hashFunc((string)key);
- for(int i = index; i < tableSize; i++){
- if((hashTable.at(i)).isEmpty() || (hashTable.at(i)).key == key) {
- hashTable.at(i) = node(key, value);
- return;
- }
- }
- hashTable.push_back(node(key, value));
- tableSize++;
- }
- string search(Elem1 key){
- int index = hashFunc((string)key);
- for(int i = index - 1; i < tableSize; i++){
- if((hashTable.at(i)).key == key) {
- return (hashTable.at(i)).value;
- }
- }
- return "";
- }
- bool del(Elem1 key){
- int index = hashFunc((string)key);
- for(int i = index; i < tableSize; i++){
- if((hashTable.at(i)).key == key) {
- hashTable.at(i) = node();
- return true;
- }
- }
- return false;
- }
- };
- }
- #endif //LR5FORKIRILL_HASHTABLE_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement