
Блок-схема алгоритма
Код программы
Программная реализация алгоритмов для решения задачи представлена ниже.
Файл App.cpp
#include "App.h"
#include "SampleClass1.h" #include "SampleClass2.h" #include <iostream> #include <string>
#include <deque>
App::App(Base* parent) : Base(parent, "root") //Конструктор класса {
};
int App::exec_app()
{
int i = 0;
std::cout << this->name << "\n";
while (this->horizontal_print(i,i!=0)) //Построение дерева горизонтальным выводом
i++;
//this->vertical_print(0);
return (0);
};
void App::Build_tree_objects()
{
std::string rootName;
std::cin >> rootName; //задаём имя корневого объекта
//std::cout << this->name << "\n";
this->name = rootName;
int i = 0;
std::string parent, child; //Переменные с названиями связанных объектов
do
{
i++;
std::cin >> parent >> child;
if ((parent != child) && (i % 2 == 1)) //Если parent не равно child и i нечетное
{
SampleClass1* temp = new SampleClass1(this-
>Find(parent), child); //Создаёт экземпляр класса SampleClass1 }
else if ((parent != child) && (i % 2 == 0)) //Если parent не
равно child и i четное
{
SampleClass2* temp = new SampleClass2(this- >Find(parent), child); //Создаём экземпляр класса SampleClass2 };
} while(parent != child); //Пока parent не равно child
};
Файл App.h
#ifndef APP_H #define APP_H
#include "Base.h"
class App : public Base
{
public:
App(Base* parent);
void Build_tree_objects(); int exec_app();
};
#endif
Файл Base.cpp
#include "Base.h" #include <iostream> #include <vector> #include <string> #include <iomanip> using namespace std;
Base::Base(Base* parent, string name) //Конструктор класса
{
this->parent = parent; //Присваиваем свойству parent значение переменной parent
this->name = name;
this->children = vector<Base*>(); //Инициализируем children пустым вектором
if (this->parent != nullptr) //Если указатель на предка не нулевой {
parent->children.push_back(this); //добавляем в список потомков
};
};
Base::~Base()
{
for (int i{0}; i < children.size(); i++)
{
delete this->children[i]; }
};
void Base::vertical_print (int depth) //Вывод сверху вниз
{
cout << setw(depth*2 + name.length()) << this->name << endl;
for (int i = 0; i < this->children.size(); i++) //для всех потомков {
this->children[i] -> vertical_print(depth+1);
};
};
bool Base::horizontal_print (int depth, bool nextline)
{
if ((depth == 0) && (this->children.size() > 0)) //Если глубина depth нулевая и у объекта есть потомки
{
if (nextline)
cout << endl;
cout << this->name;
for (int i=0; i < this->children.size(); i++)
cout << setw(children[i]->name.length()+2) << children[i]->name; //Вывод имён
return true;
}
else
if ((depth == 0) && (this->children.size() == 0)) //Если глубина depth нулевая и у объекта нет потомков
{
return false;
}
else
{
bool res = false;
for (int i=0; i < this->children.size(); i++)
if (children[i]->horizontal_print(depth-1, nextline))
res = true;
return res;
};
};
Base* Base::Find(string name) //Поиск по имени
{
if (this->name == name) //Если имя совпадает с name return this; //возвращаем указатель на себя for (int i=0; i < this->children.size(); i++) {
Base* buff = children[i]->Find(name);
if (buff != nullptr) //Если res не нулевой return buff;
};
return nullptr;
};
void Base::SetParent(Base* parent) //Определение предка
{
int indx;
if (this->parent != nullptr) //Если свойство parent не нулевое
for (int i = 0; i < this->parent->children.size(); i++)
if (this->parent->children[i] == this)
indx = i;
this->parent->children.erase(this->parent->children.begin() + indx); parent->children.push_back(this);
this->parent = parent;
};
Base* Base::GetParent(Base* parent) //Получение родителя {
return this->parent;
};
Файл Base.h
#ifndef BASE_H #define BASE_H
#include <vector> #include <string>
class Base
{
protected:
std::string name;
private:
Base* parent;
public:
std::vector<Base*> children;
Base(Base* parent, std::string name); //Конструктор класса
~Base(); //Деструктор класса
void vertical_print (int depth);
bool horizontal_print (int depth, bool nextline); //Вывод слева направо
Base* Find(std::string name); //Метод вывода по горизонтали
void SetParent (Base* parent);
Base* GetParent (Base* parent);
void setname();
std::string getname();
};
#endif
Файл main.cpp
#include "App.h" #include <iostream>
int main()
{
App ob_app(nullptr); ob_app.Build_tree_objects(); return ob_app.exec_app();
}
Файл SampleClass1.cpp
#include "SampleClass1.h" #include <string>
#include <iostream>
SampleClass1::SampleClass1(Base* parent, std::string name) : Base(parent, name) //Конструктор класса
{
};
void SampleClass1::SampleMetod1()
{
std::cout << "It is SampleMetod1!"; };
Файл SampleClass1.h
#ifndef SAMPLECLASS1_H #define SAMPLECLASS1_H
#include "Base.h" #include <string> #include <iostream>
class SampleClass1 : Base
{
public:
SampleClass1(Base* parent, std::string name); void SampleMetod1();
};
#endif
Файл SampleClass2.cpp
#include "SampleClass2.h" #include <string>
#include <iostream>
SampleClass2::SampleClass2(Base* parent, std::string name) : Base(parent, name) //Конструктор класса
{
};
void SampleClass2::SampleMetod2()
{
std::cout << "It is SampleMetod2!"; };
Файл SampleClass2.h
#ifndef SAMPLECLASS2_H #define SAMPLECLASS2_H
#include "Base.h" #include <string> #include <iostream>
class SampleClass2 : Base
{
public:
SampleClass2(Base* parent, std::string name); void SampleMetod2();
};
#endif