48 lines
1.2 KiB
C++
48 lines
1.2 KiB
C++
#include <iostream>
|
|
#include <list>
|
|
#include <vector>
|
|
#include <string>
|
|
|
|
class HashTable {
|
|
private:
|
|
static const int TABLE_SIZE = 10;
|
|
std::vector<std::list<std::pair<std::string, int>>> table;
|
|
|
|
int hashFunction(const std::string& key) {
|
|
int hash = 0;
|
|
for (char c : key) {
|
|
hash = (hash * 31 + c) % TABLE_SIZE;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
public:
|
|
HashTable() : table(TABLE_SIZE) {}
|
|
|
|
void insert(const std::string& key, int value) {
|
|
int index = hashFunction(key);
|
|
table[index].push_back(std::make_pair(key, value));
|
|
}
|
|
|
|
int search(const std::string& key) {
|
|
int index = hashFunction(key);
|
|
for (const auto& pair : table[index]) {
|
|
if (pair.first == key) {
|
|
return pair.second; // найдено значение
|
|
}
|
|
}
|
|
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;
|
|
} |