Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- #include <string>
- #include <algorithm>
- class Index {
- private:
- struct Entry {
- std::string word;
- std::vector<int> pages;
- Entry(std::string w, std::vector<int> p) : word(w), pages(p) {}
- };
- std::vector<Entry> entries;
- public:
- // Добавление записи в указатель
- void addEntry(std::string word, std::vector<int> pages) {
- Entry e(word, pages);
- entries.push_back(e);
- }
- // Вывод указателя на экран
- void printIndex() {
- for (auto e : entries) {
- std::cout << e.word << ": ";
- for (auto p : e.pages) {
- std::cout << p << " ";
- }
- std::cout << std::endl;
- }
- }
- // Поиск номеров страниц для заданного слова
- void searchWord(std::string word) {
- auto e = std::find_if(entries.begin(), entries.end(), [=](const Entry& entry) {
- return entry.word == word;
- });
- if (e != entries.end()) {
- std::cout << word << ": ";
- for (auto p : e->pages) {
- std::cout << p << " ";
- }
- std::cout << std::endl;
- } else {
- std::cout << "Слово не найдено в указателе" << std::endl;
- }
- }
- // Удаление записи из указателя
- void removeEntry(std::string word) {
- entries.erase(std::remove_if(entries.begin(), entries.end(), [=](const Entry& entry) {
- return entry.word == word;
- }), entries.end());
- }
- // Загрузка указателя из файла
- void loadIndexFromFile(std::string filename) {
- std::ifstream file(filename);
- if (file.is_open()) {
- std::string line;
- while (getline(file, line)) {
- std::string word;
- std::vector<int> pages;
- std::istringstream iss(line);
- iss >> word;
- int page;
- while (iss >> page) {
- pages.push_back(page);
- }
- addEntry(word, pages);
- }
- file.close();
- } else {
- std::cerr << "Не удалось открыть файл " << filename << std::endl;
- }
- }
- // Сохранение указателя в файл
- void saveIndexToFile(std::string filename) {
- std::ofstream file(filename);
- if (file.is_open()) {
- for (auto e : entries) {
- file << e.word << " ";
- for (auto p : e.pages) {
- file << p << " ";
- }
- file << std::endl;
- }
- file.close();
- } else {
- std::cerr << "Не удалось создать файл " << filename << std::endl;
- }
- }
- };
- int main() {
- Index index;
- // Пример добавления записей в указатель
- index.addEntry("apple", {1, 3, 5});
- index.addEntry("banana", {2, 4, 6});
- index.addEntry("cherry", {3, 6, 9});
- // Вывод указателя на экран
- index.printIndex();
- // Поиск номеров страниц для заданного слова
- index.searchWord("apple");
- // Удаление записи из указателя
- index.removeEntry("banana");
- // Вывод указателя на экран после удаления записи
- index.printIndex();
- // Загрузка указателя из файла
- index.loadIndexFromFile("index.txt");
- // Вывод указателя на экран после загрузки из файла
- index.printIndex();
- // Сохранение указателя в файл
- index.saveIndexToFile("index_new.txt");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment