#include <iostream>
#include <fstream>
#include <unordered_map>
struct HashEntry {
int key;
std::string value;
};
void saveHashTable(const std::unordered_map<int, std::string>& hashTable, const std::string& filename) {
std::ofstream file(filename, std::ios::binary);
if (file.is_open()) {
for (const auto& entry : hashTable) {
file.write(reinterpret_cast<const char*>(&entry.first), sizeof(int));
int valueSize = entry.second.size();
file.write(reinterpret_cast<const char*>(&valueSize), sizeof(int));
file.write(entry.second.c_str(), valueSize);
}
file.close();
}
}
std::unordered_map<int, std::string> loadHashTable(const std::string& filename) {
std::unordered_map<int, std::string> hashTable;
std::ifstream file(filename, std::ios::binary);
if (file.is_open()) {
while (!file.eof()) {
int key;
int valueSize;
file.read(reinterpret_cast<char*>(&key), sizeof(int));
file.read(reinterpret_cast<char*>(&valueSize), sizeof(int));
std::string value(valueSize, '\0');
file.read(&value[0], valueSize);
hashTable[key] = value;
}
file.close();
}
return hashTable;
}
int main() {
std::unordered_map<int, std::string> hashTable;
hashTable[1] = "Value 1";
hashTable[2] = "Value 2";
hashTable[3] = "Value 3";
std::string filename = "hash_table.db";
saveHashTable(hashTable, filename);
std::unordered_map<int, std::string> loadedHashTable = loadHashTable(filename);
for (const auto& entry : loadedHashTable) {
std::cout << "Key: " << entry.first << ", Value: " << entry.second << std::endl;
}
return 0;
}