65 lines
1.7 KiB
C++
65 lines
1.7 KiB
C++
#include <iostream>
|
|
#include <vector>
|
|
#include <string>
|
|
|
|
class HashTable {
|
|
private:
|
|
static const int TABLE_SIZE = 11;
|
|
std::vector<std::pair<std::string, int>> table[TABLE_SIZE];
|
|
|
|
int hashFunction1(const std::string& key) {
|
|
int hash = 0;
|
|
for (char c : key) {
|
|
hash = (hash * 31 + c) % TABLE_SIZE;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
int hashFunction2(const std::string& key) {
|
|
int hash = 0;
|
|
for (char c : key) {
|
|
hash = (hash * 17 + c) % (TABLE_SIZE - 1) + 1;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
public:
|
|
void insert(const std::string& key, int value) {
|
|
int index = hashFunction1(key);
|
|
int offset = hashFunction2(key);
|
|
|
|
while (!table[index].empty() && table[index].back().first != key) {
|
|
index = (index + offset) % TABLE_SIZE;
|
|
}
|
|
|
|
table[index].push_back(std::make_pair(key, value));
|
|
}
|
|
|
|
int search(const std::string& key) {
|
|
int index = hashFunction1(key);
|
|
int offset = hashFunction2(key);
|
|
|
|
while (!table[index].empty() && table[index].back().first != key) {
|
|
index = (index + offset) % TABLE_SIZE;
|
|
}
|
|
|
|
if (!table[index].empty() && table[index].back().first == key) {
|
|
return table[index].back().second;
|
|
}
|
|
else {
|
|
return -1; // ключ не найден
|
|
}
|
|
}
|
|
};
|
|
|
|
int main() {
|
|
HashTable ht;
|
|
|
|
ht.insert("Alice", 30);
|
|
ht.insert("Bob", 40);
|
|
|
|
std::cout << "Значение для ключа 'Alice': " << ht.search("Alice") << std::endl;
|
|
std::cout << "Значение для ключа 'Bob': " << ht.search("Bob") << std::endl;
|
|
|
|
return 0;
|
|
} |