Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef HASH_LAB_5
- #define HASH_LAB_5
- #include <iomanip>
- class Hash_table;
- class Element_of_the_hash_table;
- class hash_struct;
- class hash_struct
- {
- public:
- int value;
- unsigned int hash;
- friend std::ostream& operator<< (std::ostream &out, const hash_struct &elem);
- };
- class Element_of_the_hash_table
- {
- private:
- bool Filled;
- hash_struct _object;
- public:
- Element_of_the_hash_table()
- {
- Filled = 0;
- }
- void fill(int value, unsigned int hash)
- {
- this->_object.value = value;
- this->_object.hash = hash;
- this->Filled = 1;
- }
- operator bool() { return Filled; }
- friend Hash_table;
- };
- class Hash_table
- {
- private:
- Element_of_the_hash_table * ptr;
- unsigned int size;
- unsigned int elems;
- int first_hash(int value)
- {
- return value % this->size;
- }
- int second_hash(int value)
- {
- return value % 17;
- }
- public:
- Hash_table(unsigned int size = 2341)
- {
- this->ptr = new Element_of_the_hash_table[size];
- this->size = size;
- this->elems = 0;
- }
- unsigned int add(int value)
- {
- unsigned int try_count = 1;
- Element_of_the_hash_table * arr = this->ptr;
- unsigned int hash = first_hash(value);
- while(arr[hash])
- {
- hash += second_hash(value);
- ++try_count;
- if (hash >= this->size)
- hash %= this->size;
- }
- arr[hash].fill(value, hash) ;
- ++this->elems;
- return try_count;
- }
- bool search(int value)
- {
- unsigned int try_count = 1;
- Element_of_the_hash_table * arr = this->ptr;
- unsigned int hash = first_hash(value);
- while(arr[hash] && arr[hash]._object.value != value)
- {
- hash += second_hash(value);
- ++try_count;
- if (hash >= this->size)
- hash %= this->size;
- }
- if (arr[hash])
- return true;
- return false;
- }
- unsigned int search(int value, hash_struct &out_struct)
- {
- unsigned int try_count = 1;
- Element_of_the_hash_table * arr = this->ptr;
- unsigned int hash = first_hash(value);
- while(arr[hash] && arr[hash]._object.value != value)
- {
- hash += second_hash(value);
- ++try_count;
- if (hash >= this->size)
- hash %= this->size;
- }
- if (arr[hash])
- out_struct = arr[hash]._object;
- else
- {
- try_count = 0;
- //std::cout << "elem with value " << value << " not found" << std::endl;
- }
- return try_count;
- }
- void print()
- {
- for(int i = 0; i < this->size; ++i)
- if(this->ptr[i])
- std::cout << this->ptr[i]._object << std::endl;
- }
- ~Hash_table()
- {
- delete [](this->ptr);
- }
- };
- std::ostream& operator<< (std::ostream &out, const hash_struct &elem)
- {
- // поскольку operator<< является другом класса Point, то мы имеем прямой доступ к членам Point
- out << "value - " << std::setw(15) << std::left << elem.value << "; hash - " << elem.hash;
- return out;
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement