/
Oppq
/
Labs
Обзор
Документация
Войти
/
Oppq
/
Labs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lab8/Labsem5-6.cpp
941 строка
23 KB
Oppq
Lab8
21 май 2026, 07:41
Верифицирован
21 май 2026, 07:41
2cd3883
Код
Авторство
О чём код?
#include <iostream> #include <array> #include <vector> #include <list> #include <set> #include <map> #include <string> #include <algorithm> #include <fstream> #include <random> #include <queue> #include <unordered_set> #include <unordered_map> using namespace std; //Лаб6 struct Child { string surname; string name; string birthDate; string parents; int childrenCount; int height; int weight; string group; }; template<typename T> void show(const string& name, const T& c) { cout << name << ": "; for (auto x : c) cout << x << " "; cout << endl; } void printChild(const Child& c) { cout << c.surname << " " << c.name << "|" << c.group << "|рост " << c.height << "|вес " << c.weight << endl; } void printChildren(const string& name, const list<Child>& lst) { cout << name << ":\n"; for (const auto& c : lst) { cout << " "; printChild(c); } cout << endl; } void showMap(const string& name, const map<int, string>& m) { cout << name << ":\n"; for (auto& p : m) cout << " " << p.first << "->" << p.second << endl; } void printMap(const string& name, const multimap<int, string>& m) { cout << name << ":\n"; for (const auto& [key, val] : m) cout << " " << key << "->" << val << endl; } void printSet(const string& name, const unordered_set<int>& s) { cout << name << ": "; for (const auto& x : s) cout << x << " "; cout << " (порядок может быть совершенно любым)" << endl; } void print(const string& name, const vector<int>& v) { cout << name << ": "; for (int x : v) cout << x << " "; cout << endl; } void task2() { cout << "\nЗадание 2\n"; cout << "Вариант 8: от -5 до 5, p=10\n\n"; vector<int> nums(15); random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dist(-5, 5); for (int i = 0; i < nums.size(); i++) { nums[i] = dist(gen); } cout << "Исходный массив (после операции генерации): "; for (int x : nums) { cout << x << " "; } cout << endl; rotate(nums.rbegin(), nums.rbegin() + 2, nums.rend()); cout << "Вывод массива после сдвига: "; for (int x : nums) { cout << x << " "; } cout << endl; for (int i = 0; i < nums.size(); i++) { nums[i] = nums[i] * 10; } cout << "Элементы массива после умножения на 10: "; for (int x : nums) { cout << x << " "; } cout << endl; int p = 10; int count = 0; for (int x : nums) { if (x * x > p) { count++; } } cout << "Количество элементов с квадратом > " << p << " : " << count << endl; } struct Country { string name; string capital; bool operator==(const Country& other) const { return name == other.name && capital == other.capital; } }; struct CountryHash { size_t operator()(const Country& c) const { auto h1 = hash<string>{}(c.name); auto h2 = hash<string>{}(c.capital); return hash<tuple<string, string>>{}({c.name, c.capital}); } }; void task3() { unordered_map<Country, int, CountryHash> population; population[{"Россия", "Москва"}] = 146000000; population[{"Германия", "Берлин"}] = 83000000; population[{"Франция", "Париж"}] = 67000000; population[{"Италия", "Рим"}] = 60000000; population[{"Япония", "Токио"}] = 125000000; cout << "Население стран:\n"; for (const auto& pair : population) { cout << " " << pair.first.name << " столица " << pair.first.capital << ": " << pair.second << endl; } } int main_lab6() { setlocale(LC_ALL, "Russian"); cout << "\nARRAY:\n"; array<int, 5> a = { 1, 2, 3, 4, 5 }; array<int, 5> arr2; arr2.fill(7); array<int, 5> arr3 = a; array<int, 5> arr4; for (int i = 0; i < arr4.size(); i++) { arr4[i] = i; } auto it = find(a.begin(), a.end(), 3); if (it != a.end()) cout << "Нашли: " << *it << endl; a[2] = 33; show("array после изменения", a); array<int, 5> arrFile; ifstream arrIn("array_data.txt"); for (int i = 0; i < 5; i++) { arrIn >> arrFile[i]; } arrIn.close(); show(" - Из файла", arrFile); cout << "\nVECTOR:\n"; vector<int> v1 = { 10, 20, 30 }; vector<int> v2(3, 5); vector<int> v3; v3.push_back(100); v3.push_back(200); vector<int> v4(v1.begin(), v1.end()); v1.push_back(60); auto vit = v1.begin() + 1; v1.insert(vit, 99); show("v1 после добавления", v1); v1.erase(v1.begin() + 3); show("v1 после удаления", v1); auto vfind = find(v1.begin(), v1.end(), 40); if (vfind != v1.end()) cout << "Поиск: нашли " << *vfind << endl; v1[0] = 777; show("v1 после изменения", v1); vector<int> v5 = v1; show("v5 (копия)", v5); vector<int> vecFile; ifstream vecIn("vector_data.txt"); int va; while (vecIn >> va) vecFile.push_back(va); vecIn.close(); show("Из файла", vecFile); cout << "\nLIST:\n"; list<int> l = { 5, 4, 3, 2, 1 }; list<int> l2(5, 7); list<int> l3; l3.push_back(100); l3.push_back(200); l3.push_back(300); list<int> l4(l.begin(), l.end()); l.push_back(99); l.push_front(100); auto lit = l.begin(); advance(lit, 2); l.insert(lit, 777); show("После добавления", l); l.remove(4); show("list после удаления 4", l); auto lfind = find(l.begin(), l.end(), 3); if (lfind != l.end()) cout << "Найден элемент '3'" << endl; for (auto& x : l) if (x == 2) x = 222; show("После изменения", l); list<int> lstCopy = l; show("Копия", lstCopy); list<int> lstFile; ifstream lstIn("list_data.txt"); int lval; while (lstIn >> lval) lstFile.push_back(lval); lstIn.close(); show("Из файла", lstFile); cout << "\nSET:\n"; set<int> s1 = { 3, 1, 4, 1, 5, 9, 2 }; set<int> s2; s2.insert(10); s2.insert(20); s2.insert(30); s2.insert(7); set<int> s3(s1.begin(), s1.end()); set<int> s4; for (int i = 0; i < 5; i++) { s4.insert(i); } s1.insert(7); s1.insert(6); show("После добавления", s1); s1.erase(4); show("После удаления 4", s1); auto sit = s1.find(5); if (sit != s1.end()) { cout << " Поиск: нашли " << *sit << endl; } s1.erase(3); s1.insert(33); show("После изменения", s1); set<int> setCopy = s1; show("Копия", setCopy); set<int> setFile; ifstream setIn("set_data.txt"); int sval; while (setIn >> sval) setFile.insert(sval); setIn.close(); show(" Из файла", setFile); cout << "\nMAP:\n"; map<int, string> m = {{1, "один"}, {2, "два"}, {3, "три"}}; map<int, string> m2 ; m2[1] = "один"; m2[2] = "два"; m2[3] = "три"; m2.insert({ 4, "четыре" }); map<int, string> m3; m3.insert({5, "пять"}); m3.insert({6, "шесть"}); m3.insert({7, "семь"}); map<int, string> m4(m.begin(), m.end()); m[4] = "четыре"; m.insert({5, "пять"}); showMap("После добавления", m); m.erase(2); showMap("После удаления ключа '2'", m); auto mit = m.find(2); if (mit != m.end()) cout << "Нашли ключ 2: " << mit->second << endl; m[2] = "ДВА"; showMap("map после изменения", m); map<int, string> mapCopy = m; map<int, string> mapFile; ifstream mapIn("map_data.txt"); int key; string value; while (mapIn >> key >> value) mapFile[key] = value; mapIn.close(); cout << "\nMultiMap:\n"; multimap<int, string> mm1 = {{1, "один"}, {2, "два"}, {2, "two"}, {3, "три"}}; multimap<int, string> mm2; mm2.insert({10, "десять"}); mm2.insert({20, "двадцать"}); mm2.insert({20, "twenty"}); multimap<int, string> mm3(mm1.begin(), mm1.end()); multimap<int, string> mm4; for (int i = 0; i < 3; i++) { mm4.insert({i, "число" + to_string(i)}); mm4.insert({i, "number" + to_string(i)}); } mm1.insert({4, "четыре"}); mm1.insert({4, "four"}); showMap("После добавления", mm1); mm1.erase(2); showMap("После удаления всех с ключом 2", mm1); int key2 = 2; auto range = mm1.equal_range(key2); cout << "Поиск эл-тов с ключём " << key2 << "\n"; for (auto it = range.first; it != range.second; ++it) { cout << " " << it->first << " -> " << it->second << endl; } cout << endl; multimap<int, string> copy = mm1; auto r = mm1.equal_range(3); for (auto it = r.first; it != r.second;) { if (it->second == "три") { it = mm1.erase(it); mm1.insert({3, "ТРИ"}); } else {++it;} } multimap<int, string> mmFile; ifstream mmIn("multimap_data.txt"); int mkey; string mvalue; while (mmIn >> mkey >> mvalue) { mmFile.insert({mkey, mvalue}); } mmIn.close(); cout << "\nUNORDERED_SET:\n"; unordered_set<int> us1 = {5, 3, 8, 1, 9, 3, 2}; unordered_set<int> us2; us2.insert(10); us2.insert(20); us2.insert(30); unordered_set<int> us3(us1.begin(), us1.end()); unordered_set<int> us4; for (int i = 0; i < 5; i++) { us4.insert(i); } us1.insert(42); us1.insert(15); printSet("После добавления", us1); us1.erase(3); printSet("После удаления 3", us1); auto ufind = us1.find(5); if (ufind != us1.end()) cout << "Поиск: " << *ufind << endl; us1.erase(8); us1.insert(88); printSet("После изменения (8→88)", us1); unordered_set<int> usCopy = us1; printSet("Копия", usCopy); unordered_set<int> usFile; ifstream usIn("unordered_set_data.txt"); int uval; while (usIn >> uval) usFile.insert(uval); usIn.close(); printSet("Из файла", usFile); cout << "\nList, задание \"В\":\n"; list<Child> children = { {"Иванов", "Миша", "12.05.2019", "Иванов И.И.", 2, 110, 18, "Средняя"}, {"Петрова", "Аня", "23.03.2020", "Петрова А.А.", 1, 105, 16, "Средняя"}, {"Сидоров", "Миша", "05.12.2018", "Сидоров С.С.", 3, 115, 20, "Старшая"}, {"Кузнецова", "Оля", "17.08.2019", "Кузнецова О.О.", 2, 108, 17, "Средняя"}, {"Михайлов", "Миша", "30.01.2020", "Михайлов М.М.", 1, 102, 15, "Младшая"} }; printChildren("Дети (список иниц1)", children); list<Child> children2; children2.push_back({"Волков", "Дима", "10.10.2019", "Волков В.В.", 2, 112, 19, "Средняя"}); children2.push_back({"Соколова", "Катя", "25.05.2020", "Соколова К.К.", 1, 104, 15, "Младшая"}); printChildren("Дети (push_back, иниц2)", children2); children.push_back({"Новиков", "Петя", "15.07.2019", "Новиков П.П.", 2, 109, 18, "Средняя"}); printChildren("После добавления", children); for (auto it = children.begin(); it != children.end(); ++it) { if (it->name == "Петя") { children.erase(it); break; } } printChildren("После удаления", children); cout << "Поиск детей с именем Миша:\n"; for (auto it = children.begin(); it != children.end(); ++it) { if (it->name == "Миша") { cout << "Нашли: "; printChild(*it); } } cout << endl; for (auto& c : children) { if (c.surname == "Иванов" && c.name == "Миша") { c.height = 118; cout << "Изменён рост Миши Иванова на 118 см\n"; } } list<Child> copy_children = children; printChildren("Копия", copy_children); ifstream file("children.txt"); if (file.is_open()) { list<Child> fromFile; string s, n, bd, p, g; int cnt, h, w; while (file >> s >> n >> bd >> p >> cnt >> h >> w >> g) { fromFile.push_back({s, n, bd, p, cnt, h, w, g}); } file.close(); cout << "Загружено из файла:\n"; for (const auto& c : fromFile) { cout << " " << c.surname << " " << c.name << endl; } } else { cout << "Файл children.txt не найден\n"; } printChildren("После изменения", children); return 0; } //Лаб5 struct Data { int id; string name; }; struct Detail { string code; string name; double price; double weight; }; struct Btree { Data d; Btree* left; Btree* right; }; struct Tree { Detail det; Tree* left; Tree* right; Tree(const Detail& d) : det(d), left(nullptr), right(nullptr) {} }; Btree* addNode(Btree* theRoot, Data theData) { if (theRoot == NULL) { Btree* curNode = new Btree(); curNode->d = theData; curNode->left = NULL; curNode->right = NULL; return curNode; } if (theRoot->d.id > theData.id) { theRoot->left = addNode(theRoot->left, theData); } if (theRoot->d.id < theData.id) { theRoot->right = addNode(theRoot->right, theData); } return theRoot; } string findNode(Btree* theRoot, int theID) { if (theRoot == nullptr) { return "not found"; } if (theRoot != nullptr && theID < theRoot->d.id) { return findNode(theRoot->left, theID); } if (theRoot != nullptr && theID > theRoot->d.id) { return findNode(theRoot->right, theID); } if (theRoot != nullptr && theRoot->d.id == theID) { return theRoot->d.name; } return "not found"; } Tree* addDetail(Tree* root, Detail detail) { if (root == nullptr) { return new Tree(detail); } if (detail.code < root->det.code) { root->left = addDetail(root->left, detail); } else if (detail.code > root->det.code) { root->right = addDetail(root->right, detail); } return root; } Tree* findDetail(Tree* root, string code) { if (root == nullptr) { return nullptr; } if (code < root->det.code) { return findDetail(root->left, code); } else if (code > root->det.code) { return findDetail(root->right, code); } else { return root; } } Tree* deleteDetail(Tree* root, string code) { if (root == nullptr) return nullptr; if (code < root->det.code) { root->left = deleteDetail(root->left, code); return root; } else if (code > root->det.code) { root->right = deleteDetail(root->right, code); return root; } if (root->right == nullptr) { Tree* temp = root->left; delete root; return temp; } Tree* rightNode = root->right; if (rightNode->left == nullptr) { rightNode->left = root->left; delete root; return rightNode; } Tree* parent = rightNode; Tree* child = rightNode->left; while (child->left != nullptr) { parent = child; child = child->left; } parent->left = child->right; child->left = root->left; child->right = root->right; delete root; return child; } void deleteTree(Tree* root) { if (!root) return; deleteTree(root->left); deleteTree(root->right); delete root; } Tree* loadFromFile(Tree* root) { ifstream file("details.txt"); if (!file.is_open()) { cout << "Ошибка: файл не найден!" << endl; return root; } Detail d; int c = 0; while (file >> d.code >> d.name >> d.price >> d.weight) { root = addDetail(root, d); c++; } file.close(); cout << "Загружено " << c << " деталей из файла" << endl; return root; } Detail inputDetail() { Detail d; cout << "Шифр: "; cin >> d.code; cout << "Название: "; cin >> d.name; cout << "Цена: "; cin >> d.price; cout << "Вес: "; cin >> d.weight; return d; } Tree* deleteByPrice(Tree* root, double minPrice) { if (!root) return nullptr; root->left = deleteByPrice(root->left, minPrice); root->right = deleteByPrice(root->right, minPrice); if (root->det.price < minPrice) { cout << "Удаляем: " << root->det.name << endl; return deleteDetail(root, root->det.code); } return root; } void s1(Tree* root) { if (root == nullptr) return; cout << " Id - " << root->det.code << " "; s1(root->left); s1(root->right); } void s2(Tree* root) { if (root == nullptr) return; s2(root->left); cout << " Id - " << root->det.code << " "; s2(root->right); } void s3(Tree* root) { if (root == nullptr) return; s3(root->left); s3(root->right); cout << root->det.code << " "; } void s4(Tree* root) { if (root == nullptr) return; s4(root->right); cout << " Id - " << root->det.code << " "; s4(root->left); } void BFS(Tree* root) { if (root == nullptr) return; queue<Tree*> q; q.push(root); while (!q.empty()) { Tree* cur = q.front(); q.pop(); cout << cur->det.code << " "; if (cur->left != nullptr) { q.push(cur->left); } if (cur->right != nullptr) { q.push(cur->right); } } } void menu() { cout << "1. Добавить деталь\n"; cout << "2. Удалить деталь по шифру\n"; cout << "3. Найти деталь по шифру\n"; cout << "4. Обход в ширину\n"; cout << "5. Прямой обход\n"; cout << "6. По возрастанию\n"; cout << "7. По убыванию\n"; cout << "8. Обратный обход\n"; cout << "9. Тест добавления\n"; cout << "10. Тест поиска\n"; cout << "11. Тест удаления\n"; cout << "12. Тест загрузки из файла\n"; cout << "13. Загрузить из файла\n"; cout << "14. Удалить дешевле заданной цены" << endl; cout << "0. Выход\n"; cout << "Выбор: "; } int main_lab5() { setlocale(LC_ALL, "Russian"); Tree* root = nullptr; int choice; string code; Detail d; Tree* found; Detail d1 = {70, "Колесо", 320, 7.1}; Detail d2 = {50, "Вал", 250, 1.5}; Detail d3 = {30, "Шестерня", 180, 0.8}; Detail d4 = {20, "Втулка", 90, 0.3}; Detail d5 = {40, "Ось", 150, 0.9}; Detail d6 = {60, "Рычаг", 210, 1.2}; Detail d7 = {80, "Крышка", 120, 0.6}; do { menu(); cin >> choice; switch(choice) { case 1: d = inputDetail(); root = addDetail(root, d); cout << "Деталь добавлена" << endl; break; case 2: cout << "Шифр для удаления: "; cin >> code; root = deleteDetail(root, code); cout << "Удалено" << endl; break; case 3: cout << "Шифр для поиска: "; cin >> code; found = findDetail(root, code); if (found) {cout << "Найдено: " << found->det.name << endl;} else {cout << "Не найдено" << endl;} break; case 4: BFS(root); cout << endl; break; case 5: cout << "Прямой обход: "; s1(root); cout << endl; break; case 6: cout << "По возрастанию: "; s2(root); cout << endl; break; case 7: cout << "По убыванию: "; s4(root); cout << endl; break; case 8: cout << "Обратный обход: "; s3(root); cout << endl; break; case 9: cout << "Тест - добавление"; root = addDetail(root, d1); root = addDetail(root, d2); root = addDetail(root, d3); cout << "Добавлено 3 детали"; break; case 10: cout << "Тест - поиск"; found = findDetail(root, "50"); if (found) cout << "Найден: " << found->det.name << endl; else {cout << "Не найден";} break; case 11: cout << "Тест - удаление"; root = deleteDetail(root, "30"); cout << "Удалено\n"; break; case 12: cout << "Тест - загрузка из файла"; root = loadFromFile(root); break; case 13: root = loadFromFile(root); break; case 14: double minPrice; cout << "Минимальная цена: "; cin >> minPrice; root = deleteByPrice(root, minPrice); cout << "Удалены элементы меньше заданой цены детали" << endl; break; case 0: cout << "Программа завершена" << endl; break; default: cout << "Неверный выбор" << endl; } } while (choice != 0); deleteTree(root); return 0; } int main() { main_lab6(); main_lab5(); return 0; }