Advertisement
frogget

hash

Mar 19th, 2025
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <unordered_map>
  4. #include <cctype>
  5.  
  6. // Функция для добавления или обновления элемента в хеш-таблице
  7. void addToHashTable(std::unordered_map<char, int>& hashTable, char key) {
  8.     if (isalpha(key)) { // Проверяем, что символ является буквой
  9.         key = tolower(key); // Приводим к нижнему регистру
  10.         hashTable[key]++;
  11.     }
  12. }
  13.  
  14. // Функция для удаления элемента из хеш-таблицы
  15. void removeFromHashTable(std::unordered_map<char, int>& hashTable, char key) {
  16.     if (isalpha(key)) {
  17.         key = tolower(key);
  18.         hashTable.erase(key);
  19.     }
  20. }
  21.  
  22. // Функция для поиска элемента в хеш-таблице
  23. int searchInHashTable(const std::unordered_map<char, int>& hashTable, char key) {
  24.     if (isalpha(key)) {
  25.         key = tolower(key);
  26.         auto it = hashTable.find(key);
  27.         if (it != hashTable.end()) {
  28.             return it->second;
  29.         }
  30.     }
  31.     return 0; // Если элемент не найден
  32. }
  33.  
  34. int main() {
  35.     std::unordered_map<char, int> hashTable;
  36.     std::ifstream inputFile("input.txt");
  37.     std::ofstream outputFile("output.txt");
  38.  
  39.     if (!inputFile.is_open()) {
  40.         std::cerr << "Ошибка открытия файла input.txt" << std::endl;
  41.         return 1;
  42.     }
  43.  
  44.     if (!outputFile.is_open()) {
  45.         std::cerr << "Ошибка открытия файла output.txt" << std::endl;
  46.         return 1;
  47.     }
  48.  
  49.     // Считываем текст из файла и заполняем хеш-таблицу
  50.     char ch;
  51.     while (inputFile.get(ch)) {
  52.         addToHashTable(hashTable, ch);
  53.     }
  54.  
  55.     // Выводим хеш-таблицу в файл output.txt
  56.     for (const auto& pair : hashTable) {
  57.         outputFile << pair.first << ": " << pair.second << std::endl;
  58.     }
  59.  
  60.     // Поиск буквы в хеш-таблице
  61.     char searchChar;
  62.     std::cout << "Введите букву для поиска: ";
  63.     std::cin >> searchChar;
  64.  
  65.     int count = searchInHashTable(hashTable, searchChar);
  66.     if (count > 0) {
  67.         std::cout << "Буква '" << searchChar << "' встречается " << count << " раз(а)." << std::endl;
  68.     } else {
  69.         std::cout << "Буква '" << searchChar << "' не найдена в тексте." << std::endl;
  70.     }
  71.  
  72.     inputFile.close();
  73.     outputFile.close();
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement