From 112a0d344da9e66d20ee9ab5d488e59c5d52e6ad Mon Sep 17 00:00:00 2001 From: Angeld55 Date: Thu, 9 Apr 2020 18:09:42 +0300 Subject: added new examples --- Big4/InformaticsStudent.cpp | 103 --------- Big4/InformaticsStudent.h | 40 ---- Big4/README.md | 1 - Big4AndInheritance/Drinks/AlcoholDrink.cpp | 18 -- Big4AndInheritance/Drinks/AlcoholDrink.h | 14 -- Big4AndInheritance/Drinks/Drink.cpp | 63 ------ Big4AndInheritance/Drinks/Drink.h | 21 -- Big4AndInheritance/Drinks/main.cpp | 10 - Big4AndInheritance/Students/GradesBook.cpp | 91 -------- Big4AndInheritance/Students/GradesBook.h | 27 --- Big4AndInheritance/Students/Student.cpp | 10 - Big4AndInheritance/Students/Student.h | 15 -- Big4AndInheritance/Students/User.cpp | 43 ---- Big4AndInheritance/Students/User.h | 18 -- .../Airlines_booking_system/Airline.cpp | 110 ++++++++++ .../Airlines_booking_system/Airline.h | 28 +++ .../Airlines_booking_system/Airport.cpp | 56 +++++ .../Airlines_booking_system/Airport.h | 22 ++ .../Airlines_booking_system/Flight.cpp | 27 +++ .../Airlines_booking_system/Flight.h | 21 ++ .../Airlines_booking_system/Source.cpp | 23 ++ Big4_and_inheritance/Drinks/AlcoholDrink.cpp | 18 ++ Big4_and_inheritance/Drinks/AlcoholDrink.h | 14 ++ Big4_and_inheritance/Drinks/Drink.cpp | 63 ++++++ Big4_and_inheritance/Drinks/Drink.h | 21 ++ Big4_and_inheritance/Drinks/main.cpp | 10 + Big4_and_inheritance/Students/GradesBook.cpp | 91 ++++++++ Big4_and_inheritance/Students/GradesBook.h | 27 +++ Big4_and_inheritance/Students/Student.cpp | 10 + Big4_and_inheritance/Students/Student.h | 15 ++ Big4_and_inheritance/Students/User.cpp | 43 ++++ Big4_and_inheritance/Students/User.h | 18 ++ .../InformaticsStudent/InformaticsStudent.cpp | 103 +++++++++ .../InformaticsStudent/InformaticsStudent.h | 40 ++++ Big4_basic_examples/README.md | 1 + Big4_basic_examples/TestClass/Source.cpp | 20 ++ Big4_basic_examples/TestClass/TestClass.cpp | 45 ++++ Big4_basic_examples/TestClass/TestClass.h | 25 +++ BinaryFiles/BinaryFiles_Cheatsheet.pdf | Bin 61351 -> 0 bytes BinaryFiles/GetStructsFromBinaryFile.cpp | 47 ---- BinaryFiles/README.md | 5 - BinaryFiles/SaveAndReadStudents_BinaryFile.cpp | 47 ---- BinaryFiles/SaveStructsToBinaryFile(as array).cpp | 37 ---- BinaryFiles/SaveStructsToBinaryFile.cpp | 40 ---- BinaryFiles/Structs.bat | Bin 24 -> 0 bytes BinaryFiles/StructsBAT (how does it look).png | Bin 6050 -> 0 bytes Binary_files/BinaryFiles_Cheatsheet.pdf | Bin 0 -> 61351 bytes Binary_files/GetStructsFromBinaryFile.cpp | 47 ++++ Binary_files/README.md | 5 + Binary_files/SaveAndReadStudents_BinaryFile.cpp | 47 ++++ Binary_files/SaveStructsToBinaryFile(as array).cpp | 37 ++++ Binary_files/SaveStructsToBinaryFile.cpp | 40 ++++ Binary_files/Structs.bat | Bin 0 -> 24 bytes Binary_files/StructsBAT (how does it look).png | Bin 0 -> 6050 bytes Classes/String/String.cpp | 194 +++++++++++++++++ Classes/String/String.h | 45 ++++ Classes/String/String.hpp | 240 --------------------- Classes/Triangle/Triangle.hpp | 36 ---- Classes/Triangle/point.hpp | 23 -- DiamondProblemAndPolymorphism/Chess/Bishop.hpp | 34 --- DiamondProblemAndPolymorphism/Chess/Board.hpp | 127 ----------- DiamondProblemAndPolymorphism/Chess/Figure.hpp | 35 --- DiamondProblemAndPolymorphism/Chess/Knight.hpp | 38 ---- DiamondProblemAndPolymorphism/Chess/Queen.hpp | 25 --- DiamondProblemAndPolymorphism/Chess/README.md | 4 - DiamondProblemAndPolymorphism/Chess/Rook.hpp | 31 --- DiamondProblemAndPolymorphism/Chess/main.cpp | 16 -- DiamondProblemAndPolymorphism/sd | 1 - Diamond_problem_and_polymorphism/Chess/Bishop.hpp | 34 +++ Diamond_problem_and_polymorphism/Chess/Board.hpp | 127 +++++++++++ Diamond_problem_and_polymorphism/Chess/Figure.hpp | 35 +++ Diamond_problem_and_polymorphism/Chess/Knight.hpp | 38 ++++ Diamond_problem_and_polymorphism/Chess/Queen.hpp | 25 +++ Diamond_problem_and_polymorphism/Chess/README.md | 4 + Diamond_problem_and_polymorphism/Chess/Rook.hpp | 31 +++ Diamond_problem_and_polymorphism/Chess/main.cpp | 16 ++ Diamond_problem_and_polymorphism/sd | 1 + GetAndSet/Beer.hpp | 74 ------- Getters_and_setter_simple_examples/Beer/Beer.cpp | 43 ++++ Getters_and_setter_simple_examples/Beer/Beer.h | 27 +++ Getters_and_setter_simple_examples/Beer/main.cpp | 8 + .../Daily_schedule/Event.cpp | 40 ++++ .../Daily_schedule/Event.h | 19 ++ .../Daily_schedule/Schedule.cpp | 62 ++++++ .../Daily_schedule/Schedule.h | 19 ++ .../Daily_schedule/Source.cpp | 37 ++++ .../Daily_schedule/Time.cpp | 73 +++++++ .../Daily_schedule/Time.h | 21 ++ Homework_tasks/Homework_1.pdf | Bin 0 -> 137954 bytes Homework_tasks/Homework_2.pdf | Bin 0 -> 145320 bytes Homeworks/Homework_1.pdf | Bin 137954 -> 0 bytes Homeworks/Homework_2.pdf | Bin 145320 -> 0 bytes OperatorOverloading/Complex/Complex.hpp | 136 ------------ OperatorOverloading/Vector/Source.cpp | 14 -- OperatorOverloading/Vector/Vector.cpp | 145 ------------- OperatorOverloading/Vector/Vector.h | 37 ---- Operator_overloading/Complex/Complex.hpp | 136 ++++++++++++ Operator_overloading/Vector/Source.cpp | 14 ++ Operator_overloading/Vector/Vector.cpp | 145 +++++++++++++ Operator_overloading/Vector/Vector.h | 37 ++++ Templates/Queue.hpp | 121 ----------- Templates/Queue/Queue.hpp | 121 +++++++++++ Templates/Queue/main.cpp | 23 ++ Templates/main.cpp | 23 -- Templates/test.txt | 0 105 files changed, 2402 insertions(+), 1810 deletions(-) delete mode 100644 Big4/InformaticsStudent.cpp delete mode 100644 Big4/InformaticsStudent.h delete mode 100644 Big4/README.md delete mode 100644 Big4AndInheritance/Drinks/AlcoholDrink.cpp delete mode 100644 Big4AndInheritance/Drinks/AlcoholDrink.h delete mode 100644 Big4AndInheritance/Drinks/Drink.cpp delete mode 100644 Big4AndInheritance/Drinks/Drink.h delete mode 100644 Big4AndInheritance/Drinks/main.cpp delete mode 100644 Big4AndInheritance/Students/GradesBook.cpp delete mode 100644 Big4AndInheritance/Students/GradesBook.h delete mode 100644 Big4AndInheritance/Students/Student.cpp delete mode 100644 Big4AndInheritance/Students/Student.h delete mode 100644 Big4AndInheritance/Students/User.cpp delete mode 100644 Big4AndInheritance/Students/User.h create mode 100644 Big4_and_composition/Airlines_booking_system/Airline.cpp create mode 100644 Big4_and_composition/Airlines_booking_system/Airline.h create mode 100644 Big4_and_composition/Airlines_booking_system/Airport.cpp create mode 100644 Big4_and_composition/Airlines_booking_system/Airport.h create mode 100644 Big4_and_composition/Airlines_booking_system/Flight.cpp create mode 100644 Big4_and_composition/Airlines_booking_system/Flight.h create mode 100644 Big4_and_composition/Airlines_booking_system/Source.cpp create mode 100644 Big4_and_inheritance/Drinks/AlcoholDrink.cpp create mode 100644 Big4_and_inheritance/Drinks/AlcoholDrink.h create mode 100644 Big4_and_inheritance/Drinks/Drink.cpp create mode 100644 Big4_and_inheritance/Drinks/Drink.h create mode 100644 Big4_and_inheritance/Drinks/main.cpp create mode 100644 Big4_and_inheritance/Students/GradesBook.cpp create mode 100644 Big4_and_inheritance/Students/GradesBook.h create mode 100644 Big4_and_inheritance/Students/Student.cpp create mode 100644 Big4_and_inheritance/Students/Student.h create mode 100644 Big4_and_inheritance/Students/User.cpp create mode 100644 Big4_and_inheritance/Students/User.h create mode 100644 Big4_basic_examples/InformaticsStudent/InformaticsStudent.cpp create mode 100644 Big4_basic_examples/InformaticsStudent/InformaticsStudent.h create mode 100644 Big4_basic_examples/README.md create mode 100644 Big4_basic_examples/TestClass/Source.cpp create mode 100644 Big4_basic_examples/TestClass/TestClass.cpp create mode 100644 Big4_basic_examples/TestClass/TestClass.h delete mode 100644 BinaryFiles/BinaryFiles_Cheatsheet.pdf delete mode 100644 BinaryFiles/GetStructsFromBinaryFile.cpp delete mode 100644 BinaryFiles/README.md delete mode 100644 BinaryFiles/SaveAndReadStudents_BinaryFile.cpp delete mode 100644 BinaryFiles/SaveStructsToBinaryFile(as array).cpp delete mode 100644 BinaryFiles/SaveStructsToBinaryFile.cpp delete mode 100644 BinaryFiles/Structs.bat delete mode 100644 BinaryFiles/StructsBAT (how does it look).png create mode 100644 Binary_files/BinaryFiles_Cheatsheet.pdf create mode 100644 Binary_files/GetStructsFromBinaryFile.cpp create mode 100644 Binary_files/README.md create mode 100644 Binary_files/SaveAndReadStudents_BinaryFile.cpp create mode 100644 Binary_files/SaveStructsToBinaryFile(as array).cpp create mode 100644 Binary_files/SaveStructsToBinaryFile.cpp create mode 100644 Binary_files/Structs.bat create mode 100644 Binary_files/StructsBAT (how does it look).png create mode 100644 Classes/String/String.cpp create mode 100644 Classes/String/String.h delete mode 100644 Classes/String/String.hpp delete mode 100644 Classes/Triangle/Triangle.hpp delete mode 100644 Classes/Triangle/point.hpp delete mode 100644 DiamondProblemAndPolymorphism/Chess/Bishop.hpp delete mode 100644 DiamondProblemAndPolymorphism/Chess/Board.hpp delete mode 100644 DiamondProblemAndPolymorphism/Chess/Figure.hpp delete mode 100644 DiamondProblemAndPolymorphism/Chess/Knight.hpp delete mode 100644 DiamondProblemAndPolymorphism/Chess/Queen.hpp delete mode 100644 DiamondProblemAndPolymorphism/Chess/README.md delete mode 100644 DiamondProblemAndPolymorphism/Chess/Rook.hpp delete mode 100644 DiamondProblemAndPolymorphism/Chess/main.cpp delete mode 100644 DiamondProblemAndPolymorphism/sd create mode 100644 Diamond_problem_and_polymorphism/Chess/Bishop.hpp create mode 100644 Diamond_problem_and_polymorphism/Chess/Board.hpp create mode 100644 Diamond_problem_and_polymorphism/Chess/Figure.hpp create mode 100644 Diamond_problem_and_polymorphism/Chess/Knight.hpp create mode 100644 Diamond_problem_and_polymorphism/Chess/Queen.hpp create mode 100644 Diamond_problem_and_polymorphism/Chess/README.md create mode 100644 Diamond_problem_and_polymorphism/Chess/Rook.hpp create mode 100644 Diamond_problem_and_polymorphism/Chess/main.cpp create mode 100644 Diamond_problem_and_polymorphism/sd delete mode 100644 GetAndSet/Beer.hpp create mode 100644 Getters_and_setter_simple_examples/Beer/Beer.cpp create mode 100644 Getters_and_setter_simple_examples/Beer/Beer.h create mode 100644 Getters_and_setter_simple_examples/Beer/main.cpp create mode 100644 Getters_and_setter_simple_examples/Daily_schedule/Event.cpp create mode 100644 Getters_and_setter_simple_examples/Daily_schedule/Event.h create mode 100644 Getters_and_setter_simple_examples/Daily_schedule/Schedule.cpp create mode 100644 Getters_and_setter_simple_examples/Daily_schedule/Schedule.h create mode 100644 Getters_and_setter_simple_examples/Daily_schedule/Source.cpp create mode 100644 Getters_and_setter_simple_examples/Daily_schedule/Time.cpp create mode 100644 Getters_and_setter_simple_examples/Daily_schedule/Time.h create mode 100644 Homework_tasks/Homework_1.pdf create mode 100644 Homework_tasks/Homework_2.pdf delete mode 100644 Homeworks/Homework_1.pdf delete mode 100644 Homeworks/Homework_2.pdf delete mode 100644 OperatorOverloading/Complex/Complex.hpp delete mode 100644 OperatorOverloading/Vector/Source.cpp delete mode 100644 OperatorOverloading/Vector/Vector.cpp delete mode 100644 OperatorOverloading/Vector/Vector.h create mode 100644 Operator_overloading/Complex/Complex.hpp create mode 100644 Operator_overloading/Vector/Source.cpp create mode 100644 Operator_overloading/Vector/Vector.cpp create mode 100644 Operator_overloading/Vector/Vector.h delete mode 100644 Templates/Queue.hpp create mode 100644 Templates/Queue/Queue.hpp create mode 100644 Templates/Queue/main.cpp delete mode 100644 Templates/main.cpp create mode 100644 Templates/test.txt diff --git a/Big4/InformaticsStudent.cpp b/Big4/InformaticsStudent.cpp deleted file mode 100644 index 9073355..0000000 --- a/Big4/InformaticsStudent.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include "InformaticsStudent.h" -#include - - -bool hasDigits(const char* str,int len) -{ - for (int i = 0; i < len;i++) - { - if (str[i] >= '0' && str[i] <= '9') - return true; - } - return false; -} - -void InformaticsStudent::CopyFrom(const InformaticsStudent& other) -{ - int len = strlen(other.name); - name = new char[len + 1]; - strcpy(name, other.name); //copy name - fn = other.fn; //copy fn -} -void InformaticsStudent::Free() -{ - delete[] name; - fn = 0; -} - -InformaticsStudent::InformaticsStudent() -{ - name = nullptr; - fn = 0; -} - -InformaticsStudent::InformaticsStudent(const char* name, int fn) //При конструктура винаги КОПИРАМЕ подадения стринг за нашния нов обект. -{ // Това е важно, защото не искаме някой друг да има достъп до него. - setName(name); - setFn(fn); -} - - -InformaticsStudent::InformaticsStudent(const InformaticsStudent& other) -{ - //Използваме функцията, която копира всичко от other в нашия обект. - CopyFrom(other); - - //Понеже това е конструктор, няма нужда да трия нищо от обекта, понеже няма как да е имало данни тук,защото сега го създаваме. -} - -InformaticsStudent& InformaticsStudent::operator=(const InformaticsStudent& other) -{ - //За разлика от при Копи-контструктора , тука е имало данни , преди копирането - // (обектът да е съществувал). За това преди да копираме трябва да изтрием това, което е седяло тук. - // Проверката на 44 ред е с цел да не стане нещо от сорта T1=T1. Това би изтрило данните в обекта, защото първо трием и после - // присвояваме вече изтритите данни. - - if (this != &other) - { - Free(); //трия своята памет - - CopyFrom(other); // копирам от другия обект - } - return *this; // Връщаме указател към обекта, в който сме копирали, за може да chain-ваме T1=T2=T3. -} - -InformaticsStudent::~InformaticsStudent() -{ - Free(); -} - - -void InformaticsStudent::setName(const char* name) -{ - delete[] name; //трием данните, които са били тук. - int len = strlen(name); - if (hasDigits(name, len)) - { - this->name[0] = '\0'; - return; - } - this->name = new char[len + 1]; - strcpy(this->name, name); - - -} -void InformaticsStudent::setFn(int fn) -{ - if (fn < 45000 || fn >45999) - fn = 45000; - this->fn = fn; -} -const char* InformaticsStudent::getName() const -{ - return name; -} -int InformaticsStudent::getFn() const -{ - return fn; -} - -void InformaticsStudent::printStudent() const -{ - std::cout << name << " fn: " << fn << std::endl; -} diff --git a/Big4/InformaticsStudent.h b/Big4/InformaticsStudent.h deleted file mode 100644 index 6e9d743..0000000 --- a/Big4/InformaticsStudent.h +++ /dev/null @@ -1,40 +0,0 @@ - -// Голямта 4-ка - Функции, които трябва да разпишем, САМО когато имаме динамична памет в класа. - -// 1.Defualt constructor InformaticsStudent(); -// 2.Copy-constructor InformaticsStudent(const InformaticsStudent& other); -// 3.operator= InformaticsStudent& operator=(const InformaticsStudent& other); -// 4.Destructor ~InformaticsStudent() -// (Най-лесно е като си разпишем функция за копиране CopyFrom и функция за триене Free()) - -#pragma once -#include - -class InformaticsStudent -{ -private: - char* name; - int fn; - - void CopyFrom(const InformaticsStudent& other); - void Free(); - -public: - /// BIG 4 starts here - - InformaticsStudent(); - InformaticsStudent(const InformaticsStudent& other); - InformaticsStudent& operator=(const InformaticsStudent& other); - ~InformaticsStudent(); - // BIG 4 ends here - - InformaticsStudent(const char* name, int fn); - - void setName(const char* name); - void setFn(int fn); - const char* getName() const; - int getFn() const; - - void printStudent() const; - -}; diff --git a/Big4/README.md b/Big4/README.md deleted file mode 100644 index 8b13789..0000000 --- a/Big4/README.md +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Big4AndInheritance/Drinks/AlcoholDrink.cpp b/Big4AndInheritance/Drinks/AlcoholDrink.cpp deleted file mode 100644 index db3619c..0000000 --- a/Big4AndInheritance/Drinks/AlcoholDrink.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "AlcoholDrink.h" - - - -AlcoholDrink::AlcoholDrink(const char* mark, int ml, int percentAlcohol) : Drink(mark,ml) -{ - setAlcohol(percentAlcohol); -} -void AlcoholDrink::setAlcohol(int alcohol) -{ - if (alcohol < 4 || alcohol>98) - alcohol = 20; - percentAlcohol = alcohol; -} -int AlcoholDrink::getAlcohol() const -{ - return percentAlcohol; -} diff --git a/Big4AndInheritance/Drinks/AlcoholDrink.h b/Big4AndInheritance/Drinks/AlcoholDrink.h deleted file mode 100644 index 1bf3d66..0000000 --- a/Big4AndInheritance/Drinks/AlcoholDrink.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "Drink.h" - -class AlcoholDrink : public Drink -{ -private: - int percentAlcohol; - -public: - AlcoholDrink(const char* mark, int ml, int percentAlcohol); - void setAlcohol(int alcohol); - int AlcoholDrink::getAlcohol() const; -}; diff --git a/Big4AndInheritance/Drinks/Drink.cpp b/Big4AndInheritance/Drinks/Drink.cpp deleted file mode 100644 index a2933ad..0000000 --- a/Big4AndInheritance/Drinks/Drink.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "Drink.h" - - -void Drink::CopyFrom(const Drink& other) -{ - int len = strlen(other.mark); - mark = new char[len + 1]; - strcpy(mark, other.mark); - - ml = other.ml; -} -void Drink::Free() -{ - delete[] mark; - ml = 0; -} - -Drink::Drink() -{ - mark = new char[6]; - strcpy(mark, "Water"); - ml = 500; -} -Drink::Drink(const char* mark, int ml) -{ - int len = strlen(mark); - this->mark = new char[len + 1]; - strcpy(this->mark, mark); - - setML(ml); - -} -Drink::Drink(const Drink& other) -{ - CopyFrom(other); -} -Drink& Drink::operator=(const Drink& other) -{ - if (this != &other) - { - Free(); - CopyFrom(other); - } - return *this; -} -Drink::~Drink() -{ - Free(); -} -void Drink::setML(int ml) -{ - if (ml < 100 || ml> 1000) - ml = 500; - this->ml = ml; -} -int Drink::getML() const -{ - return ml; -} -const char* Drink::getMark() const -{ - return mark; -} diff --git a/Big4AndInheritance/Drinks/Drink.h b/Big4AndInheritance/Drinks/Drink.h deleted file mode 100644 index c02398b..0000000 --- a/Big4AndInheritance/Drinks/Drink.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include - -class Drink -{ -private: - char* mark; - int ml; - void CopyFrom(const Drink& other); - void Free(); -public: - Drink(); - Drink(const char* mark, int ml); - Drink(const Drink& other); - Drink& operator=(const Drink& other); - ~Drink(); - - void setML(int ml); - int getML() const; - const char* getMark() const; -}; diff --git a/Big4AndInheritance/Drinks/main.cpp b/Big4AndInheritance/Drinks/main.cpp deleted file mode 100644 index 6c67b96..0000000 --- a/Big4AndInheritance/Drinks/main.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "AlcoholDrink.h" -int main() -{ - AlcoholDrink DR1("Spirt", 100, 98); - - AlcoholDrink dr2 (DR1); - dr2.getMark(); - - -} diff --git a/Big4AndInheritance/Students/GradesBook.cpp b/Big4AndInheritance/Students/GradesBook.cpp deleted file mode 100644 index 759a63c..0000000 --- a/Big4AndInheritance/Students/GradesBook.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "GradesBook.h" - - -GradesBook::GradesBook() -{ - capacity = 4; - grades = new int[capacity]; - size = 0; -} -GradesBook::GradesBook(const GradesBook& other) -{ - std::cout << "Copy contr of GradesBook" << std::endl; - CopyFrom(other); -} -GradesBook& GradesBook::operator=(const GradesBook& other) -{ - if (this != &other) - { - Free(); - CopyFrom(other); - } - return *this; -} -GradesBook::~GradesBook() -{ - Free(); -} - - -void GradesBook::CopyFrom(const GradesBook& other) -{ - grades = new int[other.capacity]; - for (int i = 0; i < other.size; i++) - grades[i] = other.grades[i]; - capacity = other.capacity; - size = other.size; -} -void GradesBook::Free() -{ - delete[] grades; -} - - -bool GradesBook::isFull() -{ - return size == capacity; -} -void GradesBook::AddGrade(int grade) -{ - if (!isValidGrade(grade)) - return; - if (isFull()) - Resize(); - grades[size++] = grade; - -} -void GradesBook::Resize() -{ - int* temp = new int[capacity * 2]; - for (int i = 0; i < size; i++) - temp[i] = grades[i]; - capacity *= 2; - delete[] grades; - grades = temp; -} -void GradesBook::RemoveLastGrade() -{ - size--; -} -bool GradesBook::isValidGrade(int grade) -{ - return (grade >= 2 && grade <= 6); -} -int GradesBook::operator[](int index) const -{ - if (index < 0 || index >= size) - return -1; - return grades[index]; -} - -std::ostream& operator<<(std::ostream& stream, GradesBook& obj) -{ - for (int i = 0; i < obj.capacity; i++) - { - if (i < obj.size) - stream << obj.grades[i] << ' '; - else - stream << '_' << ' '; - } - return stream; -} \ No newline at end of file diff --git a/Big4AndInheritance/Students/GradesBook.h b/Big4AndInheritance/Students/GradesBook.h deleted file mode 100644 index e1dd262..0000000 --- a/Big4AndInheritance/Students/GradesBook.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -#include - -class GradesBook -{ - int* grades; - int size; - int capacity; - - bool isValidGrade(int grade); - void Resize(); - void CopyFrom(const GradesBook& other); - void Free(); -public: - GradesBook(); - GradesBook(const GradesBook& other); - GradesBook& operator=(const GradesBook& other); - ~GradesBook(); - - bool isFull(); - void AddGrade(int grade); - void RemoveLastGrade(); - - int operator[](int index) const; - friend std::ostream& operator<<(std::ostream& stream, GradesBook& obj); - -}; diff --git a/Big4AndInheritance/Students/Student.cpp b/Big4AndInheritance/Students/Student.cpp deleted file mode 100644 index e3d5f06..0000000 --- a/Big4AndInheritance/Students/Student.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "Student.h" -Student::Student(const char* name, int age, int fn): User(name,age) -{ - this->fn = fn; -} - -void Student::ReceiveGrade(int grade) -{ - b.AddGrade(grade); -} \ No newline at end of file diff --git a/Big4AndInheritance/Students/Student.h b/Big4AndInheritance/Students/Student.h deleted file mode 100644 index 45a103d..0000000 --- a/Big4AndInheritance/Students/Student.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -#include "User.h" -#include "GradesBook.h" - -class Student : public User -{ -public: - int fn; - GradesBook b; - - Student(const char* name, int age, int fn); - void ReceiveGrade(int grade); - - -}; diff --git a/Big4AndInheritance/Students/User.cpp b/Big4AndInheritance/Students/User.cpp deleted file mode 100644 index 27947b1..0000000 --- a/Big4AndInheritance/Students/User.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "User.h" - -/* -User::User(): name(nullptr),age(10) -{ - -} -*/ - -User::User(const char* name, int age) -{ - this->name = new char[strlen(name) + 1]; - strcpy(this->name, name); - this->age = age; -} -User::User(const User& other) -{ - cout << "Copy contr of user" << endl; - CopyFrom(other); -} -User& User::operator=(const User& other) -{ - if (this != &other) - { - Free(); - CopyFrom(other); - } - return *this; -} -User::~User() -{ - Free(); -} -void User::CopyFrom(const User& other) -{ - name = new char[strlen(other.name) + 1]; - strcpy(name, other.name); - age = other.age; -} -void User::Free() -{ - delete[] name; -} \ No newline at end of file diff --git a/Big4AndInheritance/Students/User.h b/Big4AndInheritance/Students/User.h deleted file mode 100644 index d84bd71..0000000 --- a/Big4AndInheritance/Students/User.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include -using namespace std; -class User -{ -private: - char* name; - int age; - void CopyFrom(const User& other); - void Free(); -public: - //User(); - User(const char*name, int age); - User(const User& other); - User& operator=(const User& other); - ~User(); -}; diff --git a/Big4_and_composition/Airlines_booking_system/Airline.cpp b/Big4_and_composition/Airlines_booking_system/Airline.cpp new file mode 100644 index 0000000..f5dd3e3 --- /dev/null +++ b/Big4_and_composition/Airlines_booking_system/Airline.cpp @@ -0,0 +1,110 @@ +#include "Airline.h" + +int Airline::firstFreeIndex() +{ + for (int i = 0; i < MAXFLIGHTS; i++) + { + if (fl[i] == nullptr) + return i; + } + return -1; +} +void Airline::CopyFrom(const Airline& other) +{ + name = new char[strlen(other.name) + 1]; //Копираме именето + strcpy(name, other.name); + + for (int i = 0; i < MAXFLIGHTS; i++) + { + if (other.fl[i] == nullptr) + fl[i] = nullptr; + else + { + fl[i] = new Flight(*other.fl[i]); //извикваме копи контруктора на обектите. + } // Понеже в other.fl[i] e указател, то трябва да го 'дерефрираме'. + } +} +void Airline::Free() //трябва да изтрием името и всички обекти, към които сочат указателите +{ + delete[] name; + for (int i = 0; i < MAXFLIGHTS; i++) + delete fl[i]; //някои указатели може да имат стойност nullptr, но това няма да доведе до грешка. +} + + +Airline::Airline(const char* name) +{ + this->name = new char[strlen(name) + 1]; + strcpy(this->name, name); + + for (int i = 0; i < MAXFLIGHTS; i++) + fl[i] = nullptr; +} + +bool Airline::addFlight(const char* originAirportName, const char* originAirportId, + const char* destAirportName, const char* destAirportId, int durration) +{ + int ind = firstFreeIndex(); + + if (ind == -1) //няма свободни места. + return false; + + fl[ind] = new Flight(originAirportName, originAirportId, destAirportName, destAirportId, durration); + return true; + +} +bool Airline::addFlight(const Flight& other) +{ + int ind = firstFreeIndex(); + + if (ind == -1)//няма свободни места. + return false; + fl[ind] = new Flight(other); + return true; +} +Airline::Airline(const Airline& other) +{ + CopyFrom(other); +} +Airline& Airline::operator=(const Airline& other) +{ + if (this != &other) + { + Free(); + CopyFrom(other); + } + return *this; +} +Airline::~Airline() +{ + Free(); +} +bool Airline::containsJourney(const char* originID, const char* destID) +{ + //TODO -> fix cycles + if (strcmp(originID, destID)) + return true; + + bool solution = false; + + for (int i = 0; i < MAXFLIGHTS && !solution; i++) + { + if (fl[i] != nullptr) + { + if (strcmp(fl[i]->getOrigin().getId(), originID) == 0) + solution = solution || containsJourney(fl[i]->getDestination().getId(), destID); + } + } + return false; +} +void Airline::print() +{ + for (int i = 0; i < MAXFLIGHTS; i++) + { + if (fl[i]) + { + std::cout << "Flight: "; + fl[i]->print(); + } + } +} diff --git a/Big4_and_composition/Airlines_booking_system/Airline.h b/Big4_and_composition/Airlines_booking_system/Airline.h new file mode 100644 index 0000000..0a8f34c --- /dev/null +++ b/Big4_and_composition/Airlines_booking_system/Airline.h @@ -0,0 +1,28 @@ +#include "Flight.h" + +const int MAXFLIGHTS = 10; + +class Airline +{ + char* name; + Flight* fl[MAXFLIGHTS]; //масив от указатели към обекти от тип Flight. + + int firstFreeIndex(); + + void CopyFrom(const Airline& other); + void Free(); + +public: + Airline(const char* name); + Airline(const Airline& other); + Airline& operator=(const Airline& other); + ~Airline(); + + bool addFlight(const char* originAirportName, const char* originAirportId, + const char* destAirportName, const char* destAirportId, int durration); + bool addFlight(const Flight& other); + + bool containsJourney(const char* origin, const char* dest); + + void print(); +}; diff --git a/Big4_and_composition/Airlines_booking_system/Airport.cpp b/Big4_and_composition/Airlines_booking_system/Airport.cpp new file mode 100644 index 0000000..d9f0c25 --- /dev/null +++ b/Big4_and_composition/Airlines_booking_system/Airport.cpp @@ -0,0 +1,56 @@ +#include "Airport.h" + +Airport::Airport(const char* cityName,const char* id) +{ + this->cityName = new char[strlen(cityName) + 1]; + strcpy(this->cityName, cityName); + + strcpy(this->id, id); +} + +void Airport::CopyFrom(const Airport& other) +{ + cityName = new char[strlen(other.cityName) + 1]; + strcpy(cityName, other.cityName); + + strcpy(id, other.id); //въпреки че не е динамично заделен, се налага до разпишем ръчно копирането, защото го разписваме за другите член-данни в класа. +} + +void Airport::Free() +{ + delete[] cityName; +} + +Airport::Airport(const Airport& other) +{ + CopyFrom(other); +} + +Airport& Airport::operator=(const Airport& other) +{ + if (this != &other) + { + Free(); + CopyFrom(other); + } + return *this; + +} + +Airport::~Airport() +{ + Free(); +} + +const char* Airport::getId() const +{ + return id; +} +const char* Airport::getCityName() const +{ + return cityName; +} +void Airport::print() const +{ + std::cout << cityName << '(' << id << ')'; +} diff --git a/Big4_and_composition/Airlines_booking_system/Airport.h b/Big4_and_composition/Airlines_booking_system/Airport.h new file mode 100644 index 0000000..98b3547 --- /dev/null +++ b/Big4_and_composition/Airlines_booking_system/Airport.h @@ -0,0 +1,22 @@ +#include + +class Airport +{ + + char* cityName; + char id[4]; + + void CopyFrom(const Airport& other); + void Free(); + +public: + + Airport(const char* cityName,const char* id); + Airport(const Airport& other); + Airport& operator=(const Airport& other); + ~Airport(); + + const char* getId() const; + const char* getCityName() const; + void print() const; +}; \ No newline at end of file diff --git a/Big4_and_composition/Airlines_booking_system/Flight.cpp b/Big4_and_composition/Airlines_booking_system/Flight.cpp new file mode 100644 index 0000000..b7436a3 --- /dev/null +++ b/Big4_and_composition/Airlines_booking_system/Flight.cpp @@ -0,0 +1,27 @@ +#include "Flight.h" + +Flight::Flight(const char* originAirportName, const char* originAirportId, + const char* destAirportName, const char* destAirportId, int durration) : origin(originAirportName, originAirportId), dest(destAirportName,destAirportId) +{ + this->durration = durration; +} + +Flight::Flight(const Airport& _origin, const Airport& _dest, int durration) : origin(_origin), dest(_dest) +{ + this->durration = durration; +} +const Airport& Flight::getOrigin() +{ + return origin; +} +const Airport& Flight::getDestination() +{ + return dest; +} +void Flight::print() const +{ + origin.print(); + std::cout << "-->"; + dest.print(); + std::cout << std::endl; +} \ No newline at end of file diff --git a/Big4_and_composition/Airlines_booking_system/Flight.h b/Big4_and_composition/Airlines_booking_system/Flight.h new file mode 100644 index 0000000..177aeaa --- /dev/null +++ b/Big4_and_composition/Airlines_booking_system/Flight.h @@ -0,0 +1,21 @@ +#include "Airport.h" + +class Flight +{ + + + Airport origin; + Airport dest; + int durration; + +public: + Flight(const char* originAirportName, const char* originAirportId, + const char* destAirportName, const char* destAirportId, int durration); + + Flight(const Airport& origin,const Airport& dest, int durration); + + const Airport& getOrigin(); + const Airport& getDestination(); + + void print() const; +}; \ No newline at end of file diff --git a/Big4_and_composition/Airlines_booking_system/Source.cpp b/Big4_and_composition/Airlines_booking_system/Source.cpp new file mode 100644 index 0000000..6d84dbd --- /dev/null +++ b/Big4_and_composition/Airlines_booking_system/Source.cpp @@ -0,0 +1,23 @@ + +#include "Airline.h" + + + +int main() +{ + + Airline a("Lufthansa"); + a.addFlight("Sofia", "SOF", "Berlin", "TGL", 33); + + a.addFlight("Berlin", "TGL", "London", "LTN", 55); + + a.addFlight("London", "LTN", "Sofia", "SOF", 66); + + a.addFlight("Berlin", "SCH", "Sofia", "SOF", 51); + + a.addFlight("London", "LTN", "Moscow", "MSC", 96); + + a.print(); + + +} \ No newline at end of file diff --git a/Big4_and_inheritance/Drinks/AlcoholDrink.cpp b/Big4_and_inheritance/Drinks/AlcoholDrink.cpp new file mode 100644 index 0000000..0e20087 --- /dev/null +++ b/Big4_and_inheritance/Drinks/AlcoholDrink.cpp @@ -0,0 +1,18 @@ +#include "AlcoholDrink.h" + + + +AlcoholDrink::AlcoholDrink(const char* mark, int ml, int percentAlcohol) : Drink(mark,ml) +{ + setAlcohol(percentAlcohol); +} +void AlcoholDrink::setAlcohol(int alcohol) +{ + if (alcohol < 4 || alcohol>98) + alcohol = 20; + percentAlcohol = alcohol; +} +int AlcoholDrink::getAlcohol() const +{ + return percentAlcohol; +} diff --git a/Big4_and_inheritance/Drinks/AlcoholDrink.h b/Big4_and_inheritance/Drinks/AlcoholDrink.h new file mode 100644 index 0000000..0bd1d10 --- /dev/null +++ b/Big4_and_inheritance/Drinks/AlcoholDrink.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Drink.h" + +class AlcoholDrink : public Drink +{ +private: + int percentAlcohol; + +public: + AlcoholDrink(const char* mark, int ml, int percentAlcohol); + void setAlcohol(int alcohol); + int AlcoholDrink::getAlcohol() const; +}; diff --git a/Big4_and_inheritance/Drinks/Drink.cpp b/Big4_and_inheritance/Drinks/Drink.cpp new file mode 100644 index 0000000..709446b --- /dev/null +++ b/Big4_and_inheritance/Drinks/Drink.cpp @@ -0,0 +1,63 @@ +#include "Drink.h" + + +void Drink::CopyFrom(const Drink& other) +{ + int len = strlen(other.mark); + mark = new char[len + 1]; + strcpy(mark, other.mark); + + ml = other.ml; +} +void Drink::Free() +{ + delete[] mark; + ml = 0; +} + +Drink::Drink() +{ + mark = new char[6]; + strcpy(mark, "Water"); + ml = 500; +} +Drink::Drink(const char* mark, int ml) +{ + int len = strlen(mark); + this->mark = new char[len + 1]; + strcpy(this->mark, mark); + + setML(ml); + +} +Drink::Drink(const Drink& other) +{ + CopyFrom(other); +} +Drink& Drink::operator=(const Drink& other) +{ + if (this != &other) + { + Free(); + CopyFrom(other); + } + return *this; +} +Drink::~Drink() +{ + Free(); +} +void Drink::setML(int ml) +{ + if (ml < 100 || ml> 1000) + ml = 500; + this->ml = ml; +} +int Drink::getML() const +{ + return ml; +} +const char* Drink::getMark() const +{ + return mark; +} diff --git a/Big4_and_inheritance/Drinks/Drink.h b/Big4_and_inheritance/Drinks/Drink.h new file mode 100644 index 0000000..db93c97 --- /dev/null +++ b/Big4_and_inheritance/Drinks/Drink.h @@ -0,0 +1,21 @@ +#pragma once +#include + +class Drink +{ +private: + char* mark; + int ml; + void CopyFrom(const Drink& other); + void Free(); +public: + Drink(); + Drink(const char* mark, int ml); + Drink(const Drink& other); + Drink& operator=(const Drink& other); + ~Drink(); + + void setML(int ml); + int getML() const; + const char* getMark() const; +}; diff --git a/Big4_and_inheritance/Drinks/main.cpp b/Big4_and_inheritance/Drinks/main.cpp new file mode 100644 index 0000000..c809123 --- /dev/null +++ b/Big4_and_inheritance/Drinks/main.cpp @@ -0,0 +1,10 @@ +#include "AlcoholDrink.h" +int main() +{ + AlcoholDrink DR1("Spirt", 100, 98); + + AlcoholDrink dr2 (DR1); + dr2.getMark(); + + +} diff --git a/Big4_and_inheritance/Students/GradesBook.cpp b/Big4_and_inheritance/Students/GradesBook.cpp new file mode 100644 index 0000000..6d3de27 --- /dev/null +++ b/Big4_and_inheritance/Students/GradesBook.cpp @@ -0,0 +1,91 @@ +#include "GradesBook.h" + + +GradesBook::GradesBook() +{ + capacity = 4; + grades = new int[capacity]; + size = 0; +} +GradesBook::GradesBook(const GradesBook& other) +{ + std::cout << "Copy contr of GradesBook" << std::endl; + CopyFrom(other); +} +GradesBook& GradesBook::operator=(const GradesBook& other) +{ + if (this != &other) + { + Free(); + CopyFrom(other); + } + return *this; +} +GradesBook::~GradesBook() +{ + Free(); +} + + +void GradesBook::CopyFrom(const GradesBook& other) +{ + grades = new int[other.capacity]; + for (int i = 0; i < other.size; i++) + grades[i] = other.grades[i]; + capacity = other.capacity; + size = other.size; +} +void GradesBook::Free() +{ + delete[] grades; +} + + +bool GradesBook::isFull() +{ + return size == capacity; +} +void GradesBook::AddGrade(int grade) +{ + if (!isValidGrade(grade)) + return; + if (isFull()) + Resize(); + grades[size++] = grade; + +} +void GradesBook::Resize() +{ + int* temp = new int[capacity * 2]; + for (int i = 0; i < size; i++) + temp[i] = grades[i]; + capacity *= 2; + delete[] grades; + grades = temp; +} +void GradesBook::RemoveLastGrade() +{ + size--; +} +bool GradesBook::isValidGrade(int grade) +{ + return (grade >= 2 && grade <= 6); +} +int GradesBook::operator[](int index) const +{ + if (index < 0 || index >= size) + return -1; + return grades[index]; +} + +std::ostream& operator<<(std::ostream& stream, GradesBook& obj) +{ + for (int i = 0; i < obj.capacity; i++) + { + if (i < obj.size) + stream << obj.grades[i] << ' '; + else + stream << '_' << ' '; + } + return stream; +} \ No newline at end of file diff --git a/Big4_and_inheritance/Students/GradesBook.h b/Big4_and_inheritance/Students/GradesBook.h new file mode 100644 index 0000000..e63e92f --- /dev/null +++ b/Big4_and_inheritance/Students/GradesBook.h @@ -0,0 +1,27 @@ +#pragma once +#include + +class GradesBook +{ + int* grades; + int size; + int capacity; + + bool isValidGrade(int grade); + void Resize(); + void CopyFrom(const GradesBook& other); + void Free(); +public: + GradesBook(); + GradesBook(const GradesBook& other); + GradesBook& operator=(const GradesBook& other); + ~GradesBook(); + + bool isFull(); + void AddGrade(int grade); + void RemoveLastGrade(); + + int operator[](int index) const; + friend std::ostream& operator<<(std::ostream& stream, GradesBook& obj); + +}; diff --git a/Big4_and_inheritance/Students/Student.cpp b/Big4_and_inheritance/Students/Student.cpp new file mode 100644 index 0000000..4734529 --- /dev/null +++ b/Big4_and_inheritance/Students/Student.cpp @@ -0,0 +1,10 @@ +#include "Student.h" +Student::Student(const char* name, int age, int fn): User(name,age) +{ + this->fn = fn; +} + +void Student::ReceiveGrade(int grade) +{ + b.AddGrade(grade); +} \ No newline at end of file diff --git a/Big4_and_inheritance/Students/Student.h b/Big4_and_inheritance/Students/Student.h new file mode 100644 index 0000000..aafaf58 --- /dev/null +++ b/Big4_and_inheritance/Students/Student.h @@ -0,0 +1,15 @@ +#pragma once +#include "User.h" +#include "GradesBook.h" + +class Student : public User +{ +public: + int fn; + GradesBook b; + + Student(const char* name, int age, int fn); + void ReceiveGrade(int grade); + + +}; diff --git a/Big4_and_inheritance/Students/User.cpp b/Big4_and_inheritance/Students/User.cpp new file mode 100644 index 0000000..93d34b6 --- /dev/null +++ b/Big4_and_inheritance/Students/User.cpp @@ -0,0 +1,43 @@ +#include "User.h" + +/* +User::User(): name(nullptr),age(10) +{ + +} +*/ + +User::User(const char* name, int age) +{ + this->name = new char[strlen(name) + 1]; + strcpy(this->name, name); + this->age = age; +} +User::User(const User& other) +{ + cout << "Copy contr of user" << endl; + CopyFrom(other); +} +User& User::operator=(const User& other) +{ + if (this != &other) + { + Free(); + CopyFrom(other); + } + return *this; +} +User::~User() +{ + Free(); +} +void User::CopyFrom(const User& other) +{ + name = new char[strlen(other.name) + 1]; + strcpy(name, other.name); + age = other.age; +} +void User::Free() +{ + delete[] name; +} \ No newline at end of file diff --git a/Big4_and_inheritance/Students/User.h b/Big4_and_inheritance/Students/User.h new file mode 100644 index 0000000..400057b --- /dev/null +++ b/Big4_and_inheritance/Students/User.h @@ -0,0 +1,18 @@ +#pragma once + +#include +using namespace std; +class User +{ +private: + char* name; + int age; + void CopyFrom(const User& other); + void Free(); +public: + //User(); + User(const char*name, int age); + User(const User& other); + User& operator=(const User& other); + ~User(); +}; diff --git a/Big4_basic_examples/InformaticsStudent/InformaticsStudent.cpp b/Big4_basic_examples/InformaticsStudent/InformaticsStudent.cpp new file mode 100644 index 0000000..9073355 --- /dev/null +++ b/Big4_basic_examples/InformaticsStudent/InformaticsStudent.cpp @@ -0,0 +1,103 @@ +#include "InformaticsStudent.h" +#include + + +bool hasDigits(const char* str,int len) +{ + for (int i = 0; i < len;i++) + { + if (str[i] >= '0' && str[i] <= '9') + return true; + } + return false; +} + +void InformaticsStudent::CopyFrom(const InformaticsStudent& other) +{ + int len = strlen(other.name); + name = new char[len + 1]; + strcpy(name, other.name); //copy name + fn = other.fn; //copy fn +} +void InformaticsStudent::Free() +{ + delete[] name; + fn = 0; +} + +InformaticsStudent::InformaticsStudent() +{ + name = nullptr; + fn = 0; +} + +InformaticsStudent::InformaticsStudent(const char* name, int fn) //При конструктура винаги КОПИРАМЕ подадения стринг за нашния нов обект. +{ // Това е важно, защото не искаме някой друг да има достъп до него. + setName(name); + setFn(fn); +} + + +InformaticsStudent::InformaticsStudent(const InformaticsStudent& other) +{ + //Използваме функцията, която копира всичко от other в нашия обект. + CopyFrom(other); + + //Понеже това е конструктор, няма нужда да трия нищо от обекта, понеже няма как да е имало данни тук,защото сега го създаваме. +} + +InformaticsStudent& InformaticsStudent::operator=(const InformaticsStudent& other) +{ + //За разлика от при Копи-контструктора , тука е имало данни , преди копирането + // (обектът да е съществувал). За това преди да копираме трябва да изтрием това, което е седяло тук. + // Проверката на 44 ред е с цел да не стане нещо от сорта T1=T1. Това би изтрило данните в обекта, защото първо трием и после + // присвояваме вече изтритите данни. + + if (this != &other) + { + Free(); //трия своята памет + + CopyFrom(other); // копирам от другия обект + } + return *this; // Връщаме указател към обекта, в който сме копирали, за може да chain-ваме T1=T2=T3. +} + +InformaticsStudent::~InformaticsStudent() +{ + Free(); +} + + +void InformaticsStudent::setName(const char* name) +{ + delete[] name; //трием данните, които са били тук. + int len = strlen(name); + if (hasDigits(name, len)) + { + this->name[0] = '\0'; + return; + } + this->name = new char[len + 1]; + strcpy(this->name, name); + + +} +void InformaticsStudent::setFn(int fn) +{ + if (fn < 45000 || fn >45999) + fn = 45000; + this->fn = fn; +} +const char* InformaticsStudent::getName() const +{ + return name; +} +int InformaticsStudent::getFn() const +{ + return fn; +} + +void InformaticsStudent::printStudent() const +{ + std::cout << name << " fn: " << fn << std::endl; +} diff --git a/Big4_basic_examples/InformaticsStudent/InformaticsStudent.h b/Big4_basic_examples/InformaticsStudent/InformaticsStudent.h new file mode 100644 index 0000000..6e9d743 --- /dev/null +++ b/Big4_basic_examples/InformaticsStudent/InformaticsStudent.h @@ -0,0 +1,40 @@ + +// Голямта 4-ка - Функции, които трябва да разпишем, САМО когато имаме динамична памет в класа. + +// 1.Defualt constructor InformaticsStudent(); +// 2.Copy-constructor InformaticsStudent(const InformaticsStudent& other); +// 3.operator= InformaticsStudent& operator=(const InformaticsStudent& other); +// 4.Destructor ~InformaticsStudent() +// (Най-лесно е като си разпишем функция за копиране CopyFrom и функция за триене Free()) + +#pragma once +#include + +class InformaticsStudent +{ +private: + char* name; + int fn; + + void CopyFrom(const InformaticsStudent& other); + void Free(); + +public: + /// BIG 4 starts here + + InformaticsStudent(); + InformaticsStudent(const InformaticsStudent& other); + InformaticsStudent& operator=(const InformaticsStudent& other); + ~InformaticsStudent(); + // BIG 4 ends here + + InformaticsStudent(const char* name, int fn); + + void setName(const char* name); + void setFn(int fn); + const char* getName() const; + int getFn() const; + + void printStudent() const; + +}; diff --git a/Big4_basic_examples/README.md b/Big4_basic_examples/README.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Big4_basic_examples/README.md @@ -0,0 +1 @@ + diff --git a/Big4_basic_examples/TestClass/Source.cpp b/Big4_basic_examples/TestClass/Source.cpp new file mode 100644 index 0000000..bdb8002 --- /dev/null +++ b/Big4_basic_examples/TestClass/Source.cpp @@ -0,0 +1,20 @@ +#include +#include "TestClass.h" + +using namespace std; + + +int main() +{ + TestClass obj1(3, 3, "abc"); + + TestClass obj2(obj1);//copy const; + + TestClass obj3(3, 1, "333"); + + obj3 = obj1; // operator=; + + TestClass obj4 = obj3; ////copy const; + + +} //destructors \ No newline at end of file diff --git a/Big4_basic_examples/TestClass/TestClass.cpp b/Big4_basic_examples/TestClass/TestClass.cpp new file mode 100644 index 0000000..fe5692b --- /dev/null +++ b/Big4_basic_examples/TestClass/TestClass.cpp @@ -0,0 +1,45 @@ +#include "TestClass.h" + + +TestClass::TestClass() : TestClass(0, 0, "Unknown") +{ + +} +TestClass::TestClass(int a, int b, const char* str) +{ + this->a = a; + this->b = b; + name = new char[strlen(str) + 1]; + strcpy(name, str); +} +TestClass::TestClass(const TestClass& other) +{ + CopyFrom(other); + //name = other.name NO! only the pointer will be copied. +} + +TestClass& TestClass::operator=(const TestClass& other) +{ + if (this != &other) + { + Free(); + CopyFrom(other); + } + return *this; // this TestClass* +} +TestClass::~TestClass() +{ + Free(); +} +void TestClass::CopyFrom(const TestClass& other) +{ + name = new char[strlen(other.name) + 1]; + strcpy(name, other.name); + a = other.a; + b = other.b; +} +void TestClass::Free() +{ + delete[] name; + a = b = 0; +} diff --git a/Big4_basic_examples/TestClass/TestClass.h b/Big4_basic_examples/TestClass/TestClass.h new file mode 100644 index 0000000..4841785 --- /dev/null +++ b/Big4_basic_examples/TestClass/TestClass.h @@ -0,0 +1,25 @@ +#include +class TestClass +{ +private: + + void CopyFrom(const TestClass& other); + void Free(); + int a; + int b; + char* name; + +public: + + + TestClass(int a, int b, const char* str); + + // big4 + TestClass(); + TestClass(const TestClass& other); + TestClass& operator=(const TestClass& other); + ~TestClass(); + + void Print() const; + +}; diff --git a/BinaryFiles/BinaryFiles_Cheatsheet.pdf b/BinaryFiles/BinaryFiles_Cheatsheet.pdf deleted file mode 100644 index 397177c..0000000 Binary files a/BinaryFiles/BinaryFiles_Cheatsheet.pdf and /dev/null differ diff --git a/BinaryFiles/GetStructsFromBinaryFile.cpp b/BinaryFiles/GetStructsFromBinaryFile.cpp deleted file mode 100644 index 2d91189..0000000 --- a/BinaryFiles/GetStructsFromBinaryFile.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include -using namespace std; - -struct test -{ - char ch; - int num; -}; - -int GetFileSize(ifstream& ifs) -{ - ifs.seekg(0, std::ios::end); //отиваме в края на файла - int size = ifs.tellg(); //запазваме коя е текущата позиция(тя всъщност е и размерът на файла) - ifs.seekg(0, std::ios::beg); //връщаме се в началото на файла - return size; -//тази функция е хубаво да я извикваме преди да сме чели каквото и да е от файла, понеже ще се върнем в началото и ще загубим информация до къде сме стигнали с четенето -} - - -int main() -{ - std::ifstream inF("Structs.bat", std::ios::binary); - - if (!inF.is_open()) - return false; - - int fileSize = GetFileSize(inF); // взимаме големината на файла - int objectCount = fileSize / sizeof(test); // намираме броя на обектите записани във файла - - test* arr = new test[objectCount]; - - inF.read((char*)arr, fileSize); //директно ги четем в масива - - if (!inF) - { - cout << "Error occurred while reading from the file"; - return 1; - } - inF.close(); - - for (int i = 0; i < objectCount; i++) - cout << arr[i].ch << " " << arr[i].num << endl; - delete[] arr; - - return 0; -} \ No newline at end of file diff --git a/BinaryFiles/README.md b/BinaryFiles/README.md deleted file mode 100644 index f740e9f..0000000 --- a/BinaryFiles/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# How does the binary file look like? -The file after running **SaveStructsToBinaryFile.cpp** or **SaveStructsToBinaryFile(as array).cpp** - -![Image of the binary file after running the code](https://lh3.googleusercontent.com/NcLcTEemBj6dMkOFFjUPo2jyR_7vdrUkn0dHqx8TX1CYmtW-XZzSaDwAxscJz0m3EnniPL68ag "Binary file") - diff --git a/BinaryFiles/SaveAndReadStudents_BinaryFile.cpp b/BinaryFiles/SaveAndReadStudents_BinaryFile.cpp deleted file mode 100644 index 0f600aa..0000000 --- a/BinaryFiles/SaveAndReadStudents_BinaryFile.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include - -using namespace std; -void SaveStudent(const char* name, int fn, ofstream& f) -{ - f.write((const char*)&fn, sizeof(int)); //sizeof(int) is 4 - int strLen = strlen(name); - f.write((const char*)&strLen,sizeof(int)); - f.write(name, strLen); -} -void ReadStudent(ifstream& f) -{ - int fn; - f.read((char*)&fn, sizeof(int)); - - int nameLen; - f.read((char*)&nameLen, sizeof(int)); - - char* name = new char[nameLen + 1]; - f.read(name, nameLen); - name[nameLen] = '\0'; - - cout << "Name: " << name << " Fn: " << fn << endl; - delete[] name; - -} - - - -int main() -{ - //ofstream f; - // f.open("students.bat"); - // SaveStudent("Ivan",123,f); - // SaveStudent("Sasho",555,f); - // f.close(); - - //ifstream f2; - //f2.open("students.bat"); - //ReadStudent(f2); - //ReadStudent(f2); - //f2.close(); - - - -} diff --git a/BinaryFiles/SaveStructsToBinaryFile(as array).cpp b/BinaryFiles/SaveStructsToBinaryFile(as array).cpp deleted file mode 100644 index b8d5cfe..0000000 --- a/BinaryFiles/SaveStructsToBinaryFile(as array).cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include -using namespace std; - -struct test -{ - char ch; - int num; -}; - -int main() -{ - - test arr[] = { { 'a', 4 }, { 'b', 5 }, { 'c', 6 } }; - - ofstream outF("Structs.bat", ios::binary); - - if (!outF.is_open()) - { - cout << "Error while opening file" << endl; - return 1; - } - - outF.write((const char*)&arr, sizeof(arr)); - //можем директно да запазим масива във файла. Резултатът ще същия като от SaveStructToBinaryFile.cpp - - - if (!outF.good()) - { - cout << "Error occurred while writing the file"; - return 1; - } - - outF.close(); - - return 0; -} \ No newline at end of file diff --git a/BinaryFiles/SaveStructsToBinaryFile.cpp b/BinaryFiles/SaveStructsToBinaryFile.cpp deleted file mode 100644 index 5e03b44..0000000 --- a/BinaryFiles/SaveStructsToBinaryFile.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include -using namespace std; - -struct test -{ - char ch; - int num; -}; - -int main() -{ - - test obj1{ 'a', 4 }; - test obj2{ 'b', 5 }; - test obj3{ 'c', 6 }; - - ofstream outF("Structs.bat", ios::binary); - - if (!outF.is_open()) - { - cout << "Error while opening file"< +#include +using namespace std; + +struct test +{ + char ch; + int num; +}; + +int GetFileSize(ifstream& ifs) +{ + ifs.seekg(0, std::ios::end); //отиваме в края на файла + int size = ifs.tellg(); //запазваме коя е текущата позиция(тя всъщност е и размерът на файла) + ifs.seekg(0, std::ios::beg); //връщаме се в началото на файла + return size; +//тази функция е хубаво да я извикваме преди да сме чели каквото и да е от файла, понеже ще се върнем в началото и ще загубим информация до къде сме стигнали с четенето +} + + +int main() +{ + std::ifstream inF("Structs.bat", std::ios::binary); + + if (!inF.is_open()) + return false; + + int fileSize = GetFileSize(inF); // взимаме големината на файла + int objectCount = fileSize / sizeof(test); // намираме броя на обектите записани във файла + + test* arr = new test[objectCount]; + + inF.read((char*)arr, fileSize); //директно ги четем в масива + + if (!inF) + { + cout << "Error occurred while reading from the file"; + return 1; + } + inF.close(); + + for (int i = 0; i < objectCount; i++) + cout << arr[i].ch << " " << arr[i].num << endl; + delete[] arr; + + return 0; +} \ No newline at end of file diff --git a/Binary_files/README.md b/Binary_files/README.md new file mode 100644 index 0000000..f740e9f --- /dev/null +++ b/Binary_files/README.md @@ -0,0 +1,5 @@ +# How does the binary file look like? +The file after running **SaveStructsToBinaryFile.cpp** or **SaveStructsToBinaryFile(as array).cpp** + +![Image of the binary file after running the code](https://lh3.googleusercontent.com/NcLcTEemBj6dMkOFFjUPo2jyR_7vdrUkn0dHqx8TX1CYmtW-XZzSaDwAxscJz0m3EnniPL68ag "Binary file") + diff --git a/Binary_files/SaveAndReadStudents_BinaryFile.cpp b/Binary_files/SaveAndReadStudents_BinaryFile.cpp new file mode 100644 index 0000000..0f600aa --- /dev/null +++ b/Binary_files/SaveAndReadStudents_BinaryFile.cpp @@ -0,0 +1,47 @@ +#include +#include + +using namespace std; +void SaveStudent(const char* name, int fn, ofstream& f) +{ + f.write((const char*)&fn, sizeof(int)); //sizeof(int) is 4 + int strLen = strlen(name); + f.write((const char*)&strLen,sizeof(int)); + f.write(name, strLen); +} +void ReadStudent(ifstream& f) +{ + int fn; + f.read((char*)&fn, sizeof(int)); + + int nameLen; + f.read((char*)&nameLen, sizeof(int)); + + char* name = new char[nameLen + 1]; + f.read(name, nameLen); + name[nameLen] = '\0'; + + cout << "Name: " << name << " Fn: " << fn << endl; + delete[] name; + +} + + + +int main() +{ + //ofstream f; + // f.open("students.bat"); + // SaveStudent("Ivan",123,f); + // SaveStudent("Sasho",555,f); + // f.close(); + + //ifstream f2; + //f2.open("students.bat"); + //ReadStudent(f2); + //ReadStudent(f2); + //f2.close(); + + + +} diff --git a/Binary_files/SaveStructsToBinaryFile(as array).cpp b/Binary_files/SaveStructsToBinaryFile(as array).cpp new file mode 100644 index 0000000..146a93c --- /dev/null +++ b/Binary_files/SaveStructsToBinaryFile(as array).cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +struct test +{ + char ch; + int num; +}; + +int main() +{ + + test arr[] = { { 'a', 4 }, { 'b', 5 }, { 'c', 6 } }; + + ofstream outF("Structs.bat", ios::binary); + + if (!outF.is_open()) + { + cout << "Error while opening file" << endl; + return 1; + } + + outF.write((const char*)&arr, sizeof(arr)); + //можем директно да запазим масива във файла. Резултатът ще същия като от SaveStructToBinaryFile.cpp + + + if (!outF.good()) + { + cout << "Error occurred while writing the file"; + return 1; + } + + outF.close(); + + return 0; +} \ No newline at end of file diff --git a/Binary_files/SaveStructsToBinaryFile.cpp b/Binary_files/SaveStructsToBinaryFile.cpp new file mode 100644 index 0000000..3caad14 --- /dev/null +++ b/Binary_files/SaveStructsToBinaryFile.cpp @@ -0,0 +1,40 @@ +#include +#include +using namespace std; + +struct test +{ + char ch; + int num; +}; + +int main() +{ + + test obj1{ 'a', 4 }; + test obj2{ 'b', 5 }; + test obj3{ 'c', 6 }; + + ofstream outF("Structs.bat", ios::binary); + + if (!outF.is_open()) + { + cout << "Error while opening file"<str = new char[len + 1]; + strcpy(this->str, str); +} + +String::String(const String& other) { + CopyFrom(other); +} + +String& String::operator=(const String& other) { + + if (this != &other) { + Free(); + CopyFrom(other); + } + return *this; +} + +String::~String() { + Free(); +} + +int String::getLenght() const { + return len; +} + +String String::SubString(int start) { + + if (start < 0 || start > len) + throw std::logic_error("Invalid index.\n"); + + char* newStr = new char[len - start + 2]; + int j = 0; + for (int i = start; i < len; i++) + newStr[j++] = str[i]; + newStr[j] = '\0'; + + String newString(newStr); + delete[] newStr; + + return newString; +} + +String String::SubString(int start, int end) { + + if (start < 0 || start > len || end <= 0 || end > len) + throw std::logic_error("Invalid index.\n"); + + char* newStr = new char[end - start + 2]; + int j = 0; + for (int i = start; i <= end; i++) + newStr[j++] = str[i]; + newStr[j] = '\0'; + + String newString(newStr); + delete[] newStr; + + return newString; +} + +int String::IndexOf(const String& other, int index) { + + if (index < 0) + throw std::logic_error("Invalid index.\n"); + + int iter = 0; + for (int i = index; i <= len; i++) { + + if (iter == other.len) + return i - other.len; + if (str[i] != other.str[iter]) + iter = 0; + else + iter++; + } + return -1; +} + +int String::IndexOf(const char* str, int index) { + + String searched(str); + return IndexOf(searched, index); +} + +int String::CountOcurences(String str) +{ + int count = 0; + int i = IndexOf(str, 0); + while (i != -1) + { + count++; + i = IndexOf(str, i + 1); + } + return count; +} + +inline int String::GetOcurence(String str, int num) +{ + int count = 0; + int i = IndexOf(str, 0); + while (i != -1) + { + count++; + if (count == num) + return i; + i = IndexOf(str, i + 1); + } + return count; +} + +const char& String::operator[](int index) const { + + if (index >= len) + throw std::out_of_range("Out of range!"); + return str[index]; +} + +char& String::operator[](int index) { + return str[index]; +} + +String& String::operator+=(const String& other) { + + char* temp = str; + str = new char[len + other.len + 1]; + strcpy(str, temp); + strcat(str, other.str); + len += other.len; + delete[] temp; + return *this; +} + +bool operator==(const String& lhs, const String& rhs) { + return !strcmp(lhs.str, rhs.str); +} + +bool operator!=(const String& lhs, const String& rhs) { + return strcmp(lhs.str, rhs.str); +} + +std::ostream& operator<<(std::ostream& os, const String& obj) { + return os << obj.str; +} + +std::istream& operator>>(std::istream& is, String& obj) { + + char buff[MAX_SIZE]; + is.getline(buff, MAX_SIZE); + obj.str = new char[strlen(buff) + 1]; + strcpy(obj.str, buff); + + return is; +} + + +const String operator+(const String& lhs, const String& rhs) { + if (lhs.getLenght() == 0) + return rhs; + else if (rhs.getLenght() == 0) + return lhs; + return String(lhs) += rhs; +} diff --git a/Classes/String/String.h b/Classes/String/String.h new file mode 100644 index 0000000..37bbc6d --- /dev/null +++ b/Classes/String/String.h @@ -0,0 +1,45 @@ +#ifndef STRING_HDR +#define STRING_HDR + +#include +#include + +const int MAX_SIZE = 1024; + +class String { + +private: + char* str; + int len; + + void CopyFrom(const String& other); + void Free(); + +public: + String(); + String(char ch); + String(const char* str); + String(const String& other); + String& operator=(const String& other); + ~String(); + + int getLenght() const; + String SubString(int start); + String SubString(int start, int end); + int IndexOf(const String& other, int index); //return the index of the first encounter of other in the object + int IndexOf(const char* str, int index); //reusing IndexOf(const String& other, int index) + int CountOcurences(String str); // How many times a string is found as substring + int GetOcurence(String str, int i); //Get if the i-th substring (count start from 1) + + const char& operator[](int index) const; + char& operator[](int index); + String& operator+=(const String& other); //return the concatenation of the object with other + friend bool operator==(const String& lhs, const String& rhs); //return true if two strings are equivalent + friend bool operator!=(const String& lhs, const String& rhs); //return true if two strings are not equivalent + friend std::ostream& operator<<(std::ostream& os, const String& obj); + friend std::istream& operator>>(std::istream& is, String& obj); + + String* Split(String str); +}; +const String operator+(const String& lhs, const String& rhs); +#endif // !STRING_HDR \ No newline at end of file diff --git a/Classes/String/String.hpp b/Classes/String/String.hpp deleted file mode 100644 index b2c333f..0000000 --- a/Classes/String/String.hpp +++ /dev/null @@ -1,240 +0,0 @@ -#ifndef STRING_HDR -#define STRING_HDR - -#include -#include - -const int MAX_SIZE = 1024; - -class String { - -private: - char* str; - int len; - - void CopyFrom(const String& other); - void Free(); - -public: - String(); - String(char ch); - String(const char* str); - String(const String& other); - String& operator=(const String& other); - ~String(); - - int getLenght() const; - String SubString(int start); - String SubString(int start, int end); - int IndexOf(const String& other, int index); //return the index of the first encounter of other in the object - int IndexOf(const char* str, int index); //reusing IndexOf(const String& other, int index) - int CountOcurences(String str); // How many times a string is found as substring - int GetOcurence(String str,int i); //Get if the i-th substring (count start from 1) - - const char& operator[](int index) const; - char& operator[](int index); - String& operator+=(const String& other); //return the concatenation of the object with other - friend bool operator==(const String& lhs, const String& rhs); //return true if two strings are equivalent - friend bool operator!=(const String& lhs, const String& rhs); //return true if two strings are not equivalent - friend std::ostream& operator<<(std::ostream& os, const String& obj); - friend std::istream& operator>>(std::istream& is, String& obj); - - String* Split(String str); -}; -const String operator+(const String& lhs, const String& rhs); - - -void String::CopyFrom(const String& other) { - - str = new char[strlen(other.str) + 1]; - strcpy(str, other.str); - - len = other.len; -} - -void String::Free() { - delete[] str; -} - -String::String() { - - str = new char[1]; - str[0] = '\0'; - len = 0; -} - -inline String::String(char ch) -{ - str = new char[2]; - str[0] = ch; - str[1] = '\0'; - len = 1; -} - -String::String(const char* str) { - - len = strlen(str); - - this->str = new char[len + 1]; - strcpy(this->str, str); -} - -String::String(const String& other) { - CopyFrom(other); -} - -String& String::operator=(const String& other) { - - if (this != &other) { - Free(); - CopyFrom(other); - } - return *this; -} - -String::~String() { - Free(); -} - -int String::getLenght() const { - return len; -} - -String String::SubString(int start) { - - if (start < 0 || start > len) - throw std::logic_error("Invalid index.\n"); - - char* newStr = new char[len - start + 2]; - int j = 0; - for (int i = start; i < len; i++) - newStr[j++] = str[i]; - newStr[j] = '\0'; - - String newString(newStr); - delete[] newStr; - - return newString; -} - -String String::SubString(int start, int end) { - - if (start < 0 || start > len || end <= 0 || end > len) - throw std::logic_error("Invalid index.\n"); - - char* newStr = new char[end - start + 2]; - int j = 0; - for (int i = start; i <= end; i++) - newStr[j++] = str[i]; - newStr[j] = '\0'; - - String newString(newStr); - delete[] newStr; - - return newString; -} - -int String::IndexOf(const String& other, int index) { - - if(index < 0) - throw std::logic_error("Invalid index.\n"); - - int iter = 0; - for (int i = index; i <= len; i++) { - - if (iter == other.len) - return i - other.len; - if (str[i] != other.str[iter]) - iter = 0; - else - iter++; - } - return -1; -} - -int String::IndexOf(const char* str, int index) { - - String searched(str); - return IndexOf(searched, index); -} - -int String::CountOcurences(String str) -{ - int count = 0; - int i = IndexOf(str,0); - while (i!=-1) - { - count++; - i = IndexOf(str, i + 1); - } - return count; -} - -inline int String::GetOcurence(String str, int num) -{ - int count = 0; - int i = IndexOf(str, 0); - while (i != -1) - { - count++; - if (count == num) - return i; - i = IndexOf(str, i + 1); - } - return count; -} - -const char& String::operator[](int index) const { - - if(index >= len) - throw std::out_of_range("Out of range!"); - return str[index]; -} - -char& String::operator[](int index) { - return str[index]; -} - -String& String::operator+=(const String& other) { - - char* temp = str; - str = new char[len + other.len + 1]; - strcpy(str, temp); - strcat(str, other.str); - len += other.len; - delete[] temp; - return *this; -} - -bool operator==(const String& lhs, const String& rhs) { - return !strcmp(lhs.str, rhs.str); -} - -bool operator!=(const String& lhs, const String& rhs) { - return strcmp(lhs.str, rhs.str); -} - -std::ostream& operator<<(std::ostream& os, const String& obj) { - return os << obj.str; -} - -std::istream& operator>>(std::istream& is, String& obj) { - - char buff[MAX_SIZE]; - is.getline(buff, MAX_SIZE); - obj.str = new char[strlen(buff) + 1]; - strcpy(obj.str, buff); - - return is; -} - - -const String operator+(const String& lhs, const String& rhs) { - if (lhs.getLenght() == 0) - return rhs; - else if (rhs.getLenght() == 0) - return lhs; - return String(lhs) += rhs; -} - -#endif // !STRING_HDR diff --git a/Classes/Triangle/Triangle.hpp b/Classes/Triangle/Triangle.hpp deleted file mode 100644 index ab0a8ff..0000000 --- a/Classes/Triangle/Triangle.hpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "point.hpp" - -class Triangle -{ -public: - Point p1; - Point p2; - Point p3; - //Кой конструктор е по-добре да ползваме и защо? - Triangle(Point p1, Point p2, Point p3); - Triangle(int x1,int y1,int x2,int y2,int x3,int y3); - - double getPer(); - - -}; -Triangle::Triangle(Point p1, Point p2, Point p3) -{ - this->p1 = p1; - this->p2 = p2; - this->p3 = p3; -} -Triangle::Triangle(int x1,int y1,int x2,int y2,int x3,int y3) -{ - p1.x = x1; - p1.y = y1; - p2.x = x2; - p2.y = y2; - p3.x = x3; - p3.y = y3; -} -// Използваме вече дефинираните функции, без да се интересуваме от тяхната реализация -double Triangle::getPer() -{ - return p1.DistTo(p2) + p2.DistTo(p3) + p3.DistTo(p1); -} diff --git a/Classes/Triangle/point.hpp b/Classes/Triangle/point.hpp deleted file mode 100644 index a8a2c19..0000000 --- a/Classes/Triangle/point.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#include - -struct Point -{ - Point() - { - x = 0; - y = 0; - } - Point(int x, int y) - { - this->x = x; - this->y = y; - } - double DistTo(const Point& other) - { - int dx = x - other.x; - int dy = y - other.y; - return sqrt(dx*dx + dy*dy); - } - int x; - int y; -}; \ No newline at end of file diff --git a/DiamondProblemAndPolymorphism/Chess/Bishop.hpp b/DiamondProblemAndPolymorphism/Chess/Bishop.hpp deleted file mode 100644 index b46e315..0000000 --- a/DiamondProblemAndPolymorphism/Chess/Bishop.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once -#include "Figure.hpp" - -class Bishop : virtual public Figure -{ -public: - Bishop(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite) - {} - - bool Move(int xNew, int yNew); - - void Print(); -}; -bool Bishop::Move(int xNew, int yNew) -{ - if (!isValidCoord(xNew, yNew)) - return false; - int dx = abs(xCoord - xNew); - int dy = abs(yCoord - yNew); - if (dx == dy) - { - xCoord = xNew; - yCoord = yNew; - return true; - } - return false; - - - -} -void Bishop::Print() -{ - cout << 'B'; -} \ No newline at end of file diff --git a/DiamondProblemAndPolymorphism/Chess/Board.hpp b/DiamondProblemAndPolymorphism/Chess/Board.hpp deleted file mode 100644 index 9ea5b93..0000000 --- a/DiamondProblemAndPolymorphism/Chess/Board.hpp +++ /dev/null @@ -1,127 +0,0 @@ -#pragma once -#include "Figure.hpp" -#include "Knight.hpp" -#include "Queen.hpp" - -class Board -{ - Figure*** board; - -public: - Board(); - Board(const Board& other) = delete; - Board& operator=(const Board& other) = delete; - ~Board(); - bool isEmptySquare(int x, int y) const; - bool AddKnight(int x, int y, bool isWhite); - bool AddQueen(int x, int y, bool isWhite); - bool AddBishop(int x, int y, bool isWhite); - bool AddRook(int x, int y, bool isWhite); - - void Print(); - - bool MoveFigure(int xOld, int yOld, int xNew, int yNew); - -}; -Board::Board() -{ - board = new Figure**[8]; - for (int i = 0; i < 8; ++i) - board[i] = new Figure*[8]; - - for (int i = 0; i < 8; ++i) - { - for (int j = 0; j < 8; j++) - board[i][j] = nullptr; - } - -} - -Board::~Board() -{ - for (int i = 0; i < 8; ++i) - { - for (int j = 0; j < 8; ++j) - { - delete board[i][j]; - } - delete[] board[i]; - } - delete[] board; - -} -bool Board::isEmptySquare(int x, int y) const -{ - return board[x][y] == nullptr; -} - -bool Board::AddKnight(int x, int y, bool isWhite) -{ - if (!isValidCoord(x, y) || !isEmptySquare(x, y)) - return false; - board[x][y] = new Knight(x, y, isWhite); - return true; -} -bool Board::AddQueen(int x, int y, bool isWhite) -{ - if (!isValidCoord(x, y) || !isEmptySquare(x, y)) - return false; - board[x][y] = new Queen(x, y, isWhite); - return true; -} -bool Board::AddBishop(int x, int y, bool isWhite) -{ - if (!isValidCoord(x, y) || !isEmptySquare(x, y)) - return false; - board[x][y] = new Bishop(x, y, isWhite); - return true; -} -bool Board::AddRook(int x, int y, bool isWhite) -{ - if (!isValidCoord(x, y) || !isEmptySquare(x, y)) - return false; - board[x][y] = new Rook(x, y, isWhite); - return true; -} - -void Board::Print() -{ - for (int i = 0; i < 8; ++i) - { - for (int j = 0; j < 8; ++j) - { - if (!board[i][j]) - cout << '_'; - else - board[i][j]->Print(); - - } - cout << endl; - } - cout << endl; - cout << endl; -} - -bool Board::MoveFigure(int xOld, int yOld, int xNew, int yNew) -{ - if (isEmptySquare(xOld, yOld)) //Ако няма фигура, там от където искаме да преместим - return false; - - bool res = board[xOld][yOld]->Move(xNew, yNew); //провери дали фигурата може да се премести на съответната прозиция. - if (!res)// ако не -> лъжа(ходът е невъзможен) - return false; - - if (!isEmptySquare(xNew, yNew)) - { - if (board[xOld][yOld]->isWhite ^ board[xNew][yNew]->isWhite)// ако там седи фигура от различен цвят - delete board[xNew][yNew]; //взимаме я(трием обекта) - else //ако фигурата която седи на новата позиция е от СЪЩИЯ цвят - { - board[xOld][yOld]->Move(xOld, yOld); //връщаме обратно кординатите новата фигура. Тук би възникнал проблем, ако имаме фигурата пешка. - //Това е така, понеже тя няма да може да се върне назад, ако вече е преместена. - return false; //За това примерно решение е, да се направи функция goBackwards. - } - } - board[xNew][yNew] = board[xOld][yOld]; - board[xOld][yOld] = nullptr; -} \ No newline at end of file diff --git a/DiamondProblemAndPolymorphism/Chess/Figure.hpp b/DiamondProblemAndPolymorphism/Chess/Figure.hpp deleted file mode 100644 index 2d3e73e..0000000 --- a/DiamondProblemAndPolymorphism/Chess/Figure.hpp +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -#include - -using namespace std; - -bool isValidCoord(int xCoord, int yCoord) -{ - return xCoord >= 0 && xCoord <= 7 - && yCoord >= 0 && yCoord <= 7; -} - -class Figure -{ -public: - Figure(int xCoord, int yCoord, bool isWhite); - - int xCoord; - int yCoord; - bool isWhite; - virtual bool Move(int xCoord, int yCoord) = 0; - virtual void Print() = 0; - virtual ~Figure(){}; -}; - -Figure::Figure(int xCoord, int yCoord, bool isWhite) -{ - if (isValidCoord(xCoord, yCoord)) - { - this->xCoord = xCoord; - this->yCoord = yCoord; - this->isWhite = isWhite; - } - else - throw "Ivalid coordinates"; -} \ No newline at end of file diff --git a/DiamondProblemAndPolymorphism/Chess/Knight.hpp b/DiamondProblemAndPolymorphism/Chess/Knight.hpp deleted file mode 100644 index 90f93e9..0000000 --- a/DiamondProblemAndPolymorphism/Chess/Knight.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include "Figure.hpp" - -class Knight : public Figure -{ -public: - Knight(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite) - {} - - bool Move(int xNew, int yNew); - - void Print(); -}; -bool Knight::Move(int xNew, int yNew) -{ - if (!isValidCoord(xNew, yNew)) - return false; - int possibleX[] = { 1, 1, -1, -1, 2, 2, -2, -2 }; - int possibleY[] = { 2, -2, 2, -2, 1, -1, 1, -1 }; - for (int i = 0; i < 8; ++i) - { - if (xNew == xCoord + possibleX[i] - && yNew == yCoord + possibleY[i]) - { - xCoord = xNew; - yCoord = yNew; - return true; - } - - } - return false; - -} - -void Knight::Print() -{ - cout << 'K'; -} \ No newline at end of file diff --git a/DiamondProblemAndPolymorphism/Chess/Queen.hpp b/DiamondProblemAndPolymorphism/Chess/Queen.hpp deleted file mode 100644 index ad1add4..0000000 --- a/DiamondProblemAndPolymorphism/Chess/Queen.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include "Figure.hpp" -#include "Bishop.hpp" -#include "Rook.hpp" - -class Queen : public Bishop, public Rook //Формално това НЕ Е ок. Понеже царицата НЕ Е топ и царицата НЕ Е офицер. -{ -public: - Queen(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite), Bishop(xCoordinate, yCoordinate, isWhite), Rook(xCoordinate, yCoordinate, isWhite) - {} - bool Move(int xNew, int yNew); - void Print(); -}; - -void Queen::Print() -{ - cout << 'Q'; -} -bool Queen::Move(int xNew, int yNew) // Тук сме наследили 2 функционалности. Имаме конфликт, трябва да дефинираме наша(използвайки предишните, ако искаме) -{ - bool res = Rook::Move(xNew, yNew);//Пробвай да се движиш като топ(по права линия) - if (res) //Ако е успял - вс е ок - return true; - return Bishop::Move(xNew, yNew); //Ако не си успял като топ, пробвай като офицер. -} diff --git a/DiamondProblemAndPolymorphism/Chess/README.md b/DiamondProblemAndPolymorphism/Chess/README.md deleted file mode 100644 index 97ee907..0000000 --- a/DiamondProblemAndPolymorphism/Chess/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Chess - -Not a full chess project! Just a prototype. - diff --git a/DiamondProblemAndPolymorphism/Chess/Rook.hpp b/DiamondProblemAndPolymorphism/Chess/Rook.hpp deleted file mode 100644 index d973870..0000000 --- a/DiamondProblemAndPolymorphism/Chess/Rook.hpp +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#include "Figure.hpp" - -class Rook : virtual public Figure -{ - -public: - Rook(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite) - {} - - bool Move(int xNew, int yNew); - - void Print(); - -}; - -bool Rook::Move(int xNew, int yNew) -{ - if (!isValidCoord(xNew, yNew)) - return false; - if (!(xCoord == xNew ^ yCoord == yNew)) - return false; - xCoord = xNew; - yCoord = yNew; - return true; -} - -void Rook::Print() -{ - cout << 'R'; -} \ No newline at end of file diff --git a/DiamondProblemAndPolymorphism/Chess/main.cpp b/DiamondProblemAndPolymorphism/Chess/main.cpp deleted file mode 100644 index 2caaee8..0000000 --- a/DiamondProblemAndPolymorphism/Chess/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include "Board.hpp" -using namespace std; - -int main() -{ - while (1) - { - Board b; - b.AddBishop(3, 4, true); - b.AddKnight(2, 3, false); - b.Print(); - b.MoveFigure(3, 4, 2, 3); - b.Print(); - } -} diff --git a/DiamondProblemAndPolymorphism/sd b/DiamondProblemAndPolymorphism/sd deleted file mode 100644 index 6e9f0da..0000000 --- a/DiamondProblemAndPolymorphism/sd +++ /dev/null @@ -1 +0,0 @@ -h diff --git a/Diamond_problem_and_polymorphism/Chess/Bishop.hpp b/Diamond_problem_and_polymorphism/Chess/Bishop.hpp new file mode 100644 index 0000000..014eb48 --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/Bishop.hpp @@ -0,0 +1,34 @@ +#pragma once +#include "Figure.hpp" + +class Bishop : virtual public Figure +{ +public: + Bishop(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite) + {} + + bool Move(int xNew, int yNew); + + void Print(); +}; +bool Bishop::Move(int xNew, int yNew) +{ + if (!isValidCoord(xNew, yNew)) + return false; + int dx = abs(xCoord - xNew); + int dy = abs(yCoord - yNew); + if (dx == dy) + { + xCoord = xNew; + yCoord = yNew; + return true; + } + return false; + + + +} +void Bishop::Print() +{ + cout << 'B'; +} \ No newline at end of file diff --git a/Diamond_problem_and_polymorphism/Chess/Board.hpp b/Diamond_problem_and_polymorphism/Chess/Board.hpp new file mode 100644 index 0000000..95c0f41 --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/Board.hpp @@ -0,0 +1,127 @@ +#pragma once +#include "Figure.hpp" +#include "Knight.hpp" +#include "Queen.hpp" + +class Board +{ + Figure*** board; + +public: + Board(); + Board(const Board& other) = delete; + Board& operator=(const Board& other) = delete; + ~Board(); + bool isEmptySquare(int x, int y) const; + bool AddKnight(int x, int y, bool isWhite); + bool AddQueen(int x, int y, bool isWhite); + bool AddBishop(int x, int y, bool isWhite); + bool AddRook(int x, int y, bool isWhite); + + void Print(); + + bool MoveFigure(int xOld, int yOld, int xNew, int yNew); + +}; +Board::Board() +{ + board = new Figure**[8]; + for (int i = 0; i < 8; ++i) + board[i] = new Figure*[8]; + + for (int i = 0; i < 8; ++i) + { + for (int j = 0; j < 8; j++) + board[i][j] = nullptr; + } + +} + +Board::~Board() +{ + for (int i = 0; i < 8; ++i) + { + for (int j = 0; j < 8; ++j) + { + delete board[i][j]; + } + delete[] board[i]; + } + delete[] board; + +} +bool Board::isEmptySquare(int x, int y) const +{ + return board[x][y] == nullptr; +} + +bool Board::AddKnight(int x, int y, bool isWhite) +{ + if (!isValidCoord(x, y) || !isEmptySquare(x, y)) + return false; + board[x][y] = new Knight(x, y, isWhite); + return true; +} +bool Board::AddQueen(int x, int y, bool isWhite) +{ + if (!isValidCoord(x, y) || !isEmptySquare(x, y)) + return false; + board[x][y] = new Queen(x, y, isWhite); + return true; +} +bool Board::AddBishop(int x, int y, bool isWhite) +{ + if (!isValidCoord(x, y) || !isEmptySquare(x, y)) + return false; + board[x][y] = new Bishop(x, y, isWhite); + return true; +} +bool Board::AddRook(int x, int y, bool isWhite) +{ + if (!isValidCoord(x, y) || !isEmptySquare(x, y)) + return false; + board[x][y] = new Rook(x, y, isWhite); + return true; +} + +void Board::Print() +{ + for (int i = 0; i < 8; ++i) + { + for (int j = 0; j < 8; ++j) + { + if (!board[i][j]) + cout << '_'; + else + board[i][j]->Print(); + + } + cout << endl; + } + cout << endl; + cout << endl; +} + +bool Board::MoveFigure(int xOld, int yOld, int xNew, int yNew) +{ + if (isEmptySquare(xOld, yOld)) //Ако няма фигура, там от където искаме да преместим + return false; + + bool res = board[xOld][yOld]->Move(xNew, yNew); //провери дали фигурата може да се премести на съответната прозиция. + if (!res)// ако не -> лъжа(ходът е невъзможен) + return false; + + if (!isEmptySquare(xNew, yNew)) + { + if (board[xOld][yOld]->isWhite ^ board[xNew][yNew]->isWhite)// ако там седи фигура от различен цвят + delete board[xNew][yNew]; //взимаме я(трием обекта) + else //ако фигурата която седи на новата позиция е от СЪЩИЯ цвят + { + board[xOld][yOld]->Move(xOld, yOld); //връщаме обратно кординатите новата фигура. Тук би възникнал проблем, ако имаме фигурата пешка. + //Това е така, понеже тя няма да може да се върне назад, ако вече е преместена. + return false; //За това примерно решение е, да се направи функция goBackwards. + } + } + board[xNew][yNew] = board[xOld][yOld]; + board[xOld][yOld] = nullptr; +} \ No newline at end of file diff --git a/Diamond_problem_and_polymorphism/Chess/Figure.hpp b/Diamond_problem_and_polymorphism/Chess/Figure.hpp new file mode 100644 index 0000000..e3fa89d --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/Figure.hpp @@ -0,0 +1,35 @@ +#pragma once +#include + +using namespace std; + +bool isValidCoord(int xCoord, int yCoord) +{ + return xCoord >= 0 && xCoord <= 7 + && yCoord >= 0 && yCoord <= 7; +} + +class Figure +{ +public: + Figure(int xCoord, int yCoord, bool isWhite); + + int xCoord; + int yCoord; + bool isWhite; + virtual bool Move(int xCoord, int yCoord) = 0; + virtual void Print() = 0; + virtual ~Figure(){}; +}; + +Figure::Figure(int xCoord, int yCoord, bool isWhite) +{ + if (isValidCoord(xCoord, yCoord)) + { + this->xCoord = xCoord; + this->yCoord = yCoord; + this->isWhite = isWhite; + } + else + throw "Ivalid coordinates"; +} \ No newline at end of file diff --git a/Diamond_problem_and_polymorphism/Chess/Knight.hpp b/Diamond_problem_and_polymorphism/Chess/Knight.hpp new file mode 100644 index 0000000..01b9c34 --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/Knight.hpp @@ -0,0 +1,38 @@ +#pragma once +#include "Figure.hpp" + +class Knight : public Figure +{ +public: + Knight(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite) + {} + + bool Move(int xNew, int yNew); + + void Print(); +}; +bool Knight::Move(int xNew, int yNew) +{ + if (!isValidCoord(xNew, yNew)) + return false; + int possibleX[] = { 1, 1, -1, -1, 2, 2, -2, -2 }; + int possibleY[] = { 2, -2, 2, -2, 1, -1, 1, -1 }; + for (int i = 0; i < 8; ++i) + { + if (xNew == xCoord + possibleX[i] + && yNew == yCoord + possibleY[i]) + { + xCoord = xNew; + yCoord = yNew; + return true; + } + + } + return false; + +} + +void Knight::Print() +{ + cout << 'K'; +} \ No newline at end of file diff --git a/Diamond_problem_and_polymorphism/Chess/Queen.hpp b/Diamond_problem_and_polymorphism/Chess/Queen.hpp new file mode 100644 index 0000000..2f89029 --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/Queen.hpp @@ -0,0 +1,25 @@ +#pragma once +#include "Figure.hpp" +#include "Bishop.hpp" +#include "Rook.hpp" + +class Queen : public Bishop, public Rook //Формално това НЕ Е ок. Понеже царицата НЕ Е топ и царицата НЕ Е офицер. +{ +public: + Queen(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite), Bishop(xCoordinate, yCoordinate, isWhite), Rook(xCoordinate, yCoordinate, isWhite) + {} + bool Move(int xNew, int yNew); + void Print(); +}; + +void Queen::Print() +{ + cout << 'Q'; +} +bool Queen::Move(int xNew, int yNew) // Тук сме наследили 2 функционалности. Имаме конфликт, трябва да дефинираме наша(използвайки предишните, ако искаме) +{ + bool res = Rook::Move(xNew, yNew);//Пробвай да се движиш като топ(по права линия) + if (res) //Ако е успял - вс е ок + return true; + return Bishop::Move(xNew, yNew); //Ако не си успял като топ, пробвай като офицер. +} diff --git a/Diamond_problem_and_polymorphism/Chess/README.md b/Diamond_problem_and_polymorphism/Chess/README.md new file mode 100644 index 0000000..97ee907 --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/README.md @@ -0,0 +1,4 @@ +# Chess + +Not a full chess project! Just a prototype. + diff --git a/Diamond_problem_and_polymorphism/Chess/Rook.hpp b/Diamond_problem_and_polymorphism/Chess/Rook.hpp new file mode 100644 index 0000000..5ad81c8 --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/Rook.hpp @@ -0,0 +1,31 @@ +#pragma once +#include "Figure.hpp" + +class Rook : virtual public Figure +{ + +public: + Rook(int xCoordinate, int yCoordinate, bool isWhite) :Figure(xCoordinate, yCoordinate, isWhite) + {} + + bool Move(int xNew, int yNew); + + void Print(); + +}; + +bool Rook::Move(int xNew, int yNew) +{ + if (!isValidCoord(xNew, yNew)) + return false; + if (!(xCoord == xNew ^ yCoord == yNew)) + return false; + xCoord = xNew; + yCoord = yNew; + return true; +} + +void Rook::Print() +{ + cout << 'R'; +} \ No newline at end of file diff --git a/Diamond_problem_and_polymorphism/Chess/main.cpp b/Diamond_problem_and_polymorphism/Chess/main.cpp new file mode 100644 index 0000000..2caaee8 --- /dev/null +++ b/Diamond_problem_and_polymorphism/Chess/main.cpp @@ -0,0 +1,16 @@ +#include +#include "Board.hpp" +using namespace std; + +int main() +{ + while (1) + { + Board b; + b.AddBishop(3, 4, true); + b.AddKnight(2, 3, false); + b.Print(); + b.MoveFigure(3, 4, 2, 3); + b.Print(); + } +} diff --git a/Diamond_problem_and_polymorphism/sd b/Diamond_problem_and_polymorphism/sd new file mode 100644 index 0000000..6e9f0da --- /dev/null +++ b/Diamond_problem_and_polymorphism/sd @@ -0,0 +1 @@ +h diff --git a/GetAndSet/Beer.hpp b/GetAndSet/Beer.hpp deleted file mode 100644 index ef0ed4b..0000000 --- a/GetAndSet/Beer.hpp +++ /dev/null @@ -1,74 +0,0 @@ -#include -using namespace std; - -const int MAXBEERML = 500; -const int MINBEERML = 330; - -class Beer -{ -public: - Beer(const char* mark, int ml); - - void printAddress() const; - - void printBeer() const; - void setMl(int ml); - - void setMark(const char* mark); - - int getMl() const; // const сложен тук означава, че метода не променя член-данните на класа.Съответно можем да го викаме от константни обекти - - const char* getMark() const; - -private: - - char mark[20]; //Стринг с максимална дължина 19, понеже 1 символ ни трябва за '\0' - int ml; -}; - -Beer::Beer(const char* mark, int ml) -{ - setMark(mark); - setMl(ml); -} -void Beer::printAddress() const -{ - cout << this << endl; -} -void Beer::printBeer() const -{ - cout << mark << " " << ml << endl; -} -void Beer::setMl(int ml) -{ - if (ml < MINBEERML) - ml = MINBEERML; - else if (ml > MAXBEERML) - ml = MAXBEERML; - this->ml = ml; -} -void Beer::setMark(const char* mark) -{ - int len = strlen(mark); - - if (len >= 20 || len == 0) //ако ни дадат невалидна марка на бирата (стринг с дължина >= 20 ) - this->mark[0] = '\0'; //правим марката да е празния стринг - else - strcpy(this->mark, mark); -} -int Beer::getMl() const -{ - return ml; -} -const char* Beer::getMark() const -{ - return mark; -} - - -int main() -{ - Beer t("Zagorka", 5); // 5 е невалидно количество бира. Но в конструктора извикваме setML, която се грижи в променливата да не попаднат невалидни данни. - t.setMl(330); - t.printBeer(); -} diff --git a/Getters_and_setter_simple_examples/Beer/Beer.cpp b/Getters_and_setter_simple_examples/Beer/Beer.cpp new file mode 100644 index 0000000..2eaa444 --- /dev/null +++ b/Getters_and_setter_simple_examples/Beer/Beer.cpp @@ -0,0 +1,43 @@ +#include "Beer.h" + +Beer::Beer(const char* mark, int ml) +{ + setMark(mark); + setMl(ml); +} +void Beer::printAddress() const +{ + cout << this << endl; +} +void Beer::printBeer() const +{ + cout << mark << " " << ml << endl; +} +void Beer::setMl(int ml) +{ + if (ml < MINBEERML) + ml = MINBEERML; + else if (ml > MAXBEERML) + ml = MAXBEERML; + this->ml = ml; +} +void Beer::setMark(const char* mark) +{ + int len = strlen(mark); + + if (len >= 20 || len == 0) //àêî íè äàäàò íåâàëèäíà ìàðêà íà áèðàòà (ñòðèíã ñ äúëæèíà >= 20 ) + this->mark[0] = '\0'; //ïðàâèì ìàðêàòà äà å ïðàçíèÿ ñòðèíã + else + strcpy(this->mark, mark); +} +int Beer::getMl() const +{ + return ml; +} +const char* Beer::getMark() const +{ + return mark; +} + + + diff --git a/Getters_and_setter_simple_examples/Beer/Beer.h b/Getters_and_setter_simple_examples/Beer/Beer.h new file mode 100644 index 0000000..4bc8adc --- /dev/null +++ b/Getters_and_setter_simple_examples/Beer/Beer.h @@ -0,0 +1,27 @@ +#include +using namespace std; + +const int MAXBEERML = 500; +const int MINBEERML = 330; + +class Beer +{ +public: + Beer(const char* mark, int ml); + + void printAddress() const; + + void printBeer() const; + void setMl(int ml); + + void setMark(const char* mark); + + int getMl() const; // const сложен тук означава, че метода не променя член-данните на класа.Съответно можем да го викаме от константни обекти + + const char* getMark() const; + +private: + + char mark[20]; //Стринг с максимална дължина 19, понеже 1 символ ни трябва за '\0' + int ml; +}; diff --git a/Getters_and_setter_simple_examples/Beer/main.cpp b/Getters_and_setter_simple_examples/Beer/main.cpp new file mode 100644 index 0000000..9e6801d --- /dev/null +++ b/Getters_and_setter_simple_examples/Beer/main.cpp @@ -0,0 +1,8 @@ +#include "Beer.h" + +int main() +{ + Beer t("Zagorka", 5); // 5 å íåâàëèäíî êîëè÷åñòâî áèðà. Íî â êîíñòðóêòîðà èçâèêâàìå setML, êîÿòî ñå ãðèæè â ïðîìåíëèâàòà äà íå ïîïàäíàò íåâàëèäíè äàííè. + t.setMl(330); + t.printBeer(); +} \ No newline at end of file diff --git a/Getters_and_setter_simple_examples/Daily_schedule/Event.cpp b/Getters_and_setter_simple_examples/Daily_schedule/Event.cpp new file mode 100644 index 0000000..084c7b3 --- /dev/null +++ b/Getters_and_setter_simple_examples/Daily_schedule/Event.cpp @@ -0,0 +1,40 @@ +#include "Event.h" + + +Event::Event() :start(0, 0, 0), end(0, 0, 0), isInit(false) +{ } +Event::Event(const char* name, int startHours, int startMin, int startSec, int endHours, int endMin, int endSec) : start(startHours, startMin, startSec), end(endHours, endMin, endSec) +{ + if (!IsValid()) + end = start; + strcpy(this->name, name); + +} +void Event::print() const +{ + std::cout << name << std::endl; + std::cout << "start: "; + start.print(); + std::cout << "end: "; + end.print(); +} +const Time& Event::getStart() const +{ + return start; +} +const Time& Event::getEnd() const +{ + return end; +} +const char* Event::getName() const +{ + return name; +} +bool Event::getIsInit() const +{ + return isInit; +} +bool Event::IsValid() +{ + return start.CompareTo( end) >= 0; +} \ No newline at end of file diff --git a/Getters_and_setter_simple_examples/Daily_schedule/Event.h b/Getters_and_setter_simple_examples/Daily_schedule/Event.h new file mode 100644 index 0000000..32c332d --- /dev/null +++ b/Getters_and_setter_simple_examples/Daily_schedule/Event.h @@ -0,0 +1,19 @@ +#include "Time.h" + +class Event +{ + char name[30]; + Time start; + Time end; + bool isInit; +public: + Event(); + Event(const char* name, int startHours, int startMin, int startSec, int endHours, int endMin, int endSec); + bool IsValid(); + void print() const; + const Time& getStart() const; + const Time& getEnd() const; + const char* getName() const; + bool getIsInit() const; +}; + diff --git a/Getters_and_setter_simple_examples/Daily_schedule/Schedule.cpp b/Getters_and_setter_simple_examples/Daily_schedule/Schedule.cpp new file mode 100644 index 0000000..b4c9017 --- /dev/null +++ b/Getters_and_setter_simple_examples/Daily_schedule/Schedule.cpp @@ -0,0 +1,62 @@ +#include "Schedule.h" + +int Schedule::getFirstFreeSlotIndex() +{ + for (int i = 0; i < MAXEVENTS; i++) + { + if (!events[i].getIsInit()) + return i; + } + return -1; +} +void Schedule::DeleteEvent(int ind) +{ + Event emptyEvent; + events[ind] = emptyEvent; +} + +bool Schedule::AddEvent(const char* name, int startHours, int startMin, int startSec, int endHours, int endMin, int endSec) +{ + int freeIndex = getFirstFreeSlotIndex(); + if (freeIndex == -1) + return false; + Event eventToAdd(name, startHours, startMin, startSec, endHours, endMin, endSec); + events[freeIndex] = eventToAdd; + + return true; +} +bool Schedule::RemoveEvent(const char* name) +{ + for (int i = 0; i < MAXEVENTS; i++) + { + if (strcmp(events[i].getName(), name) == 0) + { + DeleteEvent(i); + return true; + } + } + return false; +} +bool Schedule::RemoveEvent(int startHours, int startMin, int startSec, int endHours, int endMin, int endSec) +{ + Time startToRemove(startHours, startMin, startSec); + Time endToRemove(endHours, endMin, endSec); + + for (int i = 0; i < MAXEVENTS; i++) + { + if ((events[i].getStart().CompareTo(startToRemove)) == 0 && (events[i].getEnd().CompareTo(endToRemove) == 0)) + { + DeleteEvent(i); + return true; + } + } + return false; +} +void Schedule::Print() const +{ + for (int i = 0; i < MAXEVENTS; i++) + { + if (events[i].getIsInit()) + events[i].print(); + } +} \ No newline at end of file diff --git a/Getters_and_setter_simple_examples/Daily_schedule/Schedule.h b/Getters_and_setter_simple_examples/Daily_schedule/Schedule.h new file mode 100644 index 0000000..2ad2c7a --- /dev/null +++ b/Getters_and_setter_simple_examples/Daily_schedule/Schedule.h @@ -0,0 +1,19 @@ +#include "Event.h" + +const int MAXEVENTS = 10; +class Schedule +{ +private: + Event events[MAXEVENTS]; + + int getFirstFreeSlotIndex(); + void DeleteEvent(int ind); + + +public: + bool AddEvent(const char* name, int startHours, int startMin, int startSec, int endHours, int endMin, int endSec); + bool RemoveEvent(const char* name); + bool RemoveEvent(int startHours, int startMin, int startSec, int endHours, int endMin, int endSec); + void Print() const; + bool isValidSchedule() const; +}; diff --git a/Getters_and_setter_simple_examples/Daily_schedule/Source.cpp b/Getters_and_setter_simple_examples/Daily_schedule/Source.cpp new file mode 100644 index 0000000..678eb98 --- /dev/null +++ b/Getters_and_setter_simple_examples/Daily_schedule/Source.cpp @@ -0,0 +1,37 @@ +#include +using namespace std; + + +#include "Schedule.h" + //àáñòðàêöèÿ + //êàïñóëàöèÿ -> + +// äíåâåí Îðã -> ñúáèòèÿ +// Ñúáèòèå -> íà÷àëåí ÷àñ è êðàåí ÷àñ +// Ìîäèôèêàòîðè çà äîñòúï: private, public: +// Êëàñ: Ñòðóêòóðà, ïðè êîÿòî ìîä. çà äîñòúï å private ïî default + + + +int main() +{ + + Schedule s; + + cout<< s.AddEvent("Party", 22, 30, 00, 23, 30, 00); + + cout<< s.AddEvent("Uni", 12, 00, 00, 14, 00, 00); + + s.AddEvent("Lunch", 11, 30, 00, 12, 00, 00); + s.Print(); + cout << "after remove"< 59) + seconds = 0; + this->seconds = seconds; +} +void Time::setMins(int mins) +{ + if (mins < 0 || mins > 59) + mins = 0; + this->mins = mins; +} +void Time::setHours(int hours) +{ + if (hours < 0 || hours > 23) + hours = 0; + this->hours = hours; +} +int Time::CompareTo(const Time& other) const +{ + if (getHours() > other.getHours()) + return -1; + else if (getHours() < other.getHours()) + { + return 1; + } + else + { + if (getMins() > other.getMins()) + return -1; + else if (getMins() < other.getMins()) + return 1; + else + { + if (getSeconds() > other.getSeconds()) + return -1; + else if (getSeconds() < other.getSeconds()) + return 1; + else + return 0; + } + } +} \ No newline at end of file diff --git a/Getters_and_setter_simple_examples/Daily_schedule/Time.h b/Getters_and_setter_simple_examples/Daily_schedule/Time.h new file mode 100644 index 0000000..97529e0 --- /dev/null +++ b/Getters_and_setter_simple_examples/Daily_schedule/Time.h @@ -0,0 +1,21 @@ +#include + +class Time +{ + int seconds; + int mins; + int hours; +public: + Time(int hours, int mins, int seconds); + //Time(); + int getSeconds() const; + int getMins() const; + int getHours() const; + void setSeconds(int seconds); + void setMins(int mins); + void setHours(int hours); + + void print() const; + + int CompareTo(const Time& other) const; +}; diff --git a/Homework_tasks/Homework_1.pdf b/Homework_tasks/Homework_1.pdf new file mode 100644 index 0000000..8383550 Binary files /dev/null and b/Homework_tasks/Homework_1.pdf differ diff --git a/Homework_tasks/Homework_2.pdf b/Homework_tasks/Homework_2.pdf new file mode 100644 index 0000000..d36ee1b Binary files /dev/null and b/Homework_tasks/Homework_2.pdf differ diff --git a/Homeworks/Homework_1.pdf b/Homeworks/Homework_1.pdf deleted file mode 100644 index 8383550..0000000 Binary files a/Homeworks/Homework_1.pdf and /dev/null differ diff --git a/Homeworks/Homework_2.pdf b/Homeworks/Homework_2.pdf deleted file mode 100644 index d36ee1b..0000000 Binary files a/Homeworks/Homework_2.pdf and /dev/null differ diff --git a/OperatorOverloading/Complex/Complex.hpp b/OperatorOverloading/Complex/Complex.hpp deleted file mode 100644 index 8a6edd5..0000000 --- a/OperatorOverloading/Complex/Complex.hpp +++ /dev/null @@ -1,136 +0,0 @@ -#include -class Complex -{ -private: - double real; - double im; - -public: - Complex(); - Complex(double real, double im); - - Complex getConjugated() const; //връща комплексно спрегнатото число на текущия обект. - - //assignment operators - // a+=b Към а се добавя стойността на b. а се променя , b не се. Операцията ще върне a за да може да се правят верижни изрази (a+=b+=c) - Complex& operator+=(const Complex&); - Complex& operator-=(const Complex&); - Complex& operator*=(const Complex&); - Complex& operator/=(const Complex&); - - - - //stream opeartors ( std::cout>> c1) (std::cin<>(std::istream&, Complex&); - -}; -// a+b. Операторът връща НОВА променлива(Complex), която е резултатът от операцията. -Complex operator+(const Complex&, const Complex&); -Complex operator-(const Complex&, const Complex&); -Complex operator*(const Complex&, const Complex&); -Complex operator/(const Complex&, const Complex&); - - - -Complex::Complex() -{ - real = 0; - im = 0; -} -Complex::Complex(double real, double im) -{ - this->real = real; - this->im = im; -} -Complex& Complex::operator+=(const Complex& other) -{ - real += other.real; - im += other.im; - return *this; -} -Complex& Complex::operator-=(const Complex& other) -{ - real -= other.real; - im -= other.im; - return *this; -} -Complex& Complex::operator*=(const Complex& other) -{ - int oldReal = real; - real = real*other.real - im*other.im; - im = oldReal*other.im + im * other.real; - return *this; -} -Complex& Complex::operator/=(const Complex& other) // a/=b -{ - Complex Conjugated = other.getConjugated(); //взимаме комплексно спрегнатата на другата дроб (b) - - Complex otherCopy(other);// копираме другата (b), за да не я промяняме. - - //Умножаваме двете по комплексно спрегнатата. - *this *= Conjugated; - otherCopy *= Conjugated; //Тук трябва да остане само реална част. - - if (otherCopy.real != 0) - { - real /= otherCopy.real; - im /= otherCopy.real; - } - - return *this; -} - -//След дефинирането на +=, -=, *= и /=, можем лесно да дефинираме +, -, * и /, преизползвайки вече написаните опратори. - - -Complex operator+(const Complex& lhs, const Complex& rhs) { //a+b - - Complex result(lhs); // Създаваме нов обект, който е копие на a (използваме копи-конструктора) - result += rhs; //към копието на a, добавяме b (Използваме вече дефинирания оператор +=) - - return result; -} -//Операторите -, *, / са аналогични с +. -Complex operator-(const Complex& lhs, const Complex& rhs) { - Complex result(lhs); - result -= rhs; - - return result; -} - -Complex operator*(const Complex& lhs, const Complex& rhs) { - - Complex result(lhs); - result *= rhs; - - return result; -} - -Complex operator/(const Complex& lhs, const Complex& rhs) { - - Complex result(lhs); - result /= rhs; - - return result; -} - -Complex Complex::getConjugated() const -{ - Complex result(*this); - result.im *= -1; - - return result; -} - -// за да можем да правим cout<>c1 или да четем от файл и др. -std::istream& operator>>(std::istream& ifs, Complex& r) { - - return ifs >> r.real >> r.im; -} diff --git a/OperatorOverloading/Vector/Source.cpp b/OperatorOverloading/Vector/Source.cpp deleted file mode 100644 index 02b3dd5..0000000 --- a/OperatorOverloading/Vector/Source.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include "Vector.h" -int main() -{ - - - Vector v1(2); - - std::cin >> v1; - - std::cout << (v1); - - -} diff --git a/OperatorOverloading/Vector/Vector.cpp b/OperatorOverloading/Vector/Vector.cpp deleted file mode 100644 index 397cd46..0000000 --- a/OperatorOverloading/Vector/Vector.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "Vector.h" - -Vector::Vector() :coordinates(nullptr), length(0) -{} -Vector::Vector(int len) -{ - coordinates = new int[len]; - for (int i = 0; i < len; i++) - coordinates[i] = 0; - length = len; -} -void Vector::CopyFrom(const Vector& other) -{ - coordinates = new int[other.length]; - for (int i = 0; i < other.GetLen(); i++) - coordinates[i] = other.coordinates[i]; - length = other.length; -} -void Vector::Free() -{ - delete[] coordinates; - length = 0; -} -Vector::Vector(const Vector& other) -{ - CopyFrom(other); -} -Vector& Vector::operator=(const Vector& other) -{ - if (this != &other) - { - Free(); - CopyFrom(other); - } - return *this; -} -Vector::~Vector() -{ - Free(); -} - -int& Vector::operator[](int index) -{ - if (index < length) - return coordinates[index]; - else - throw 0; -} -void Vector::print() -{ - std::cout << '('; - for (int i = 0; i < length; i++) - std::cout << coordinates[i]<<" "; - std::cout <<')' < a*K=b (K е константа). -{ - double coeff = lhs.GetAtIndex(0) / rhs.GetAtIndex(0); - for (int i = 1; i < lhs.GetLen(); i++) - { - if (lhs.GetAtIndex(i) == 0 || rhs.GetAtIndex(i) == 0) - continue; - double Newfirst = lhs.GetAtIndex(i); - double Newcoeff = Newfirst / rhs.GetAtIndex(i); - if (abs(Newcoeff-coeff)>0.01) - return false; - } - return true; -} -bool operator|=(const Vector& lhs, const Vector& rhs) -{ - return lhs%rhs == 0; //скаларното произведение на два успоредни вектора е 0. -} - -std::ostream& operator<<(std::ostream& os, const Vector& v) -{ - for (int i = 0; i < v.GetLen(); ++i) - os << v.GetAtIndex(i) << " "; - return os; -} - -std::istream& operator>>(std::istream& ifs, Vector& v) -{ - for (int i = 0; i < v.GetLen(); ++i) - ifs >> v[i]; - return ifs; -} diff --git a/OperatorOverloading/Vector/Vector.h b/OperatorOverloading/Vector/Vector.h deleted file mode 100644 index 03969d8..0000000 --- a/OperatorOverloading/Vector/Vector.h +++ /dev/null @@ -1,37 +0,0 @@ -#include -class Vector -{ -private: - int* coordinates; - int length; - void CopyFrom(const Vector& other); - void Free(); -public: - Vector(); - Vector(int len); - - Vector(const Vector& other); - Vector& operator=(const Vector& other); - ~Vector(); - - int GetLen() const; - - Vector& operator+=(const Vector& other); - Vector& operator-=(const Vector& other); - Vector& operator*=(int); - - friend std::ostream& operator<<(std::ostream&, const Vector& v); - friend std::istream& operator>>(std::istream&, Vector& v); - - int GetAtIndex(int index) const; - int& operator[](int index);// оператор за индексиране(като в масивите) vector a; a[4] -взима четвъртия кординат на вектора - void print(); -}; - -Vector operator+(const Vector& lhs, const Vector& rhs);// Събиране на два вектора -Vector operator-(const Vector& lhs, const Vector& rhs);// Изваждане на два вектора - -int operator%(const Vector& lhs, const Vector& rhs); // Скаларно произведение на два вектора - -bool operator||(const Vector& lhs, const Vector& rhs); // Дали два вектора са успоредни -bool operator|=(const Vector& lhs, const Vector& rhs); // Дали два вектора са перпендикулярни diff --git a/Operator_overloading/Complex/Complex.hpp b/Operator_overloading/Complex/Complex.hpp new file mode 100644 index 0000000..8a6edd5 --- /dev/null +++ b/Operator_overloading/Complex/Complex.hpp @@ -0,0 +1,136 @@ +#include +class Complex +{ +private: + double real; + double im; + +public: + Complex(); + Complex(double real, double im); + + Complex getConjugated() const; //връща комплексно спрегнатото число на текущия обект. + + //assignment operators + // a+=b Към а се добавя стойността на b. а се променя , b не се. Операцията ще върне a за да може да се правят верижни изрази (a+=b+=c) + Complex& operator+=(const Complex&); + Complex& operator-=(const Complex&); + Complex& operator*=(const Complex&); + Complex& operator/=(const Complex&); + + + + //stream opeartors ( std::cout>> c1) (std::cin<>(std::istream&, Complex&); + +}; +// a+b. Операторът връща НОВА променлива(Complex), която е резултатът от операцията. +Complex operator+(const Complex&, const Complex&); +Complex operator-(const Complex&, const Complex&); +Complex operator*(const Complex&, const Complex&); +Complex operator/(const Complex&, const Complex&); + + + +Complex::Complex() +{ + real = 0; + im = 0; +} +Complex::Complex(double real, double im) +{ + this->real = real; + this->im = im; +} +Complex& Complex::operator+=(const Complex& other) +{ + real += other.real; + im += other.im; + return *this; +} +Complex& Complex::operator-=(const Complex& other) +{ + real -= other.real; + im -= other.im; + return *this; +} +Complex& Complex::operator*=(const Complex& other) +{ + int oldReal = real; + real = real*other.real - im*other.im; + im = oldReal*other.im + im * other.real; + return *this; +} +Complex& Complex::operator/=(const Complex& other) // a/=b +{ + Complex Conjugated = other.getConjugated(); //взимаме комплексно спрегнатата на другата дроб (b) + + Complex otherCopy(other);// копираме другата (b), за да не я промяняме. + + //Умножаваме двете по комплексно спрегнатата. + *this *= Conjugated; + otherCopy *= Conjugated; //Тук трябва да остане само реална част. + + if (otherCopy.real != 0) + { + real /= otherCopy.real; + im /= otherCopy.real; + } + + return *this; +} + +//След дефинирането на +=, -=, *= и /=, можем лесно да дефинираме +, -, * и /, преизползвайки вече написаните опратори. + + +Complex operator+(const Complex& lhs, const Complex& rhs) { //a+b + + Complex result(lhs); // Създаваме нов обект, който е копие на a (използваме копи-конструктора) + result += rhs; //към копието на a, добавяме b (Използваме вече дефинирания оператор +=) + + return result; +} +//Операторите -, *, / са аналогични с +. +Complex operator-(const Complex& lhs, const Complex& rhs) { + Complex result(lhs); + result -= rhs; + + return result; +} + +Complex operator*(const Complex& lhs, const Complex& rhs) { + + Complex result(lhs); + result *= rhs; + + return result; +} + +Complex operator/(const Complex& lhs, const Complex& rhs) { + + Complex result(lhs); + result /= rhs; + + return result; +} + +Complex Complex::getConjugated() const +{ + Complex result(*this); + result.im *= -1; + + return result; +} + +// за да можем да правим cout<>c1 или да четем от файл и др. +std::istream& operator>>(std::istream& ifs, Complex& r) { + + return ifs >> r.real >> r.im; +} diff --git a/Operator_overloading/Vector/Source.cpp b/Operator_overloading/Vector/Source.cpp new file mode 100644 index 0000000..c2e3c70 --- /dev/null +++ b/Operator_overloading/Vector/Source.cpp @@ -0,0 +1,14 @@ +#include +#include "Vector.h" +int main() +{ + + + Vector v1(2); + + std::cin >> v1; + + std::cout << (v1); + + +} diff --git a/Operator_overloading/Vector/Vector.cpp b/Operator_overloading/Vector/Vector.cpp new file mode 100644 index 0000000..5059a66 --- /dev/null +++ b/Operator_overloading/Vector/Vector.cpp @@ -0,0 +1,145 @@ +#include "Vector.h" + +Vector::Vector() :coordinates(nullptr), length(0) +{} +Vector::Vector(int len) +{ + coordinates = new int[len]; + for (int i = 0; i < len; i++) + coordinates[i] = 0; + length = len; +} +void Vector::CopyFrom(const Vector& other) +{ + coordinates = new int[other.length]; + for (int i = 0; i < other.GetLen(); i++) + coordinates[i] = other.coordinates[i]; + length = other.length; +} +void Vector::Free() +{ + delete[] coordinates; + length = 0; +} +Vector::Vector(const Vector& other) +{ + CopyFrom(other); +} +Vector& Vector::operator=(const Vector& other) +{ + if (this != &other) + { + Free(); + CopyFrom(other); + } + return *this; +} +Vector::~Vector() +{ + Free(); +} + +int& Vector::operator[](int index) +{ + if (index < length) + return coordinates[index]; + else + throw 0; +} +void Vector::print() +{ + std::cout << '('; + for (int i = 0; i < length; i++) + std::cout << coordinates[i]<<" "; + std::cout <<')' < a*K=b (K е константа). +{ + double coeff = lhs.GetAtIndex(0) / rhs.GetAtIndex(0); + for (int i = 1; i < lhs.GetLen(); i++) + { + if (lhs.GetAtIndex(i) == 0 || rhs.GetAtIndex(i) == 0) + continue; + double Newfirst = lhs.GetAtIndex(i); + double Newcoeff = Newfirst / rhs.GetAtIndex(i); + if (abs(Newcoeff-coeff)>0.01) + return false; + } + return true; +} +bool operator|=(const Vector& lhs, const Vector& rhs) +{ + return lhs%rhs == 0; //скаларното произведение на два успоредни вектора е 0. +} + +std::ostream& operator<<(std::ostream& os, const Vector& v) +{ + for (int i = 0; i < v.GetLen(); ++i) + os << v.GetAtIndex(i) << " "; + return os; +} + +std::istream& operator>>(std::istream& ifs, Vector& v) +{ + for (int i = 0; i < v.GetLen(); ++i) + ifs >> v[i]; + return ifs; +} diff --git a/Operator_overloading/Vector/Vector.h b/Operator_overloading/Vector/Vector.h new file mode 100644 index 0000000..b8dbd20 --- /dev/null +++ b/Operator_overloading/Vector/Vector.h @@ -0,0 +1,37 @@ +#include +class Vector +{ +private: + int* coordinates; + int length; + void CopyFrom(const Vector& other); + void Free(); +public: + Vector(); + Vector(int len); + + Vector(const Vector& other); + Vector& operator=(const Vector& other); + ~Vector(); + + int GetLen() const; + + Vector& operator+=(const Vector& other); + Vector& operator-=(const Vector& other); + Vector& operator*=(int); + + friend std::ostream& operator<<(std::ostream&, const Vector& v); + friend std::istream& operator>>(std::istream&, Vector& v); + + int GetAtIndex(int index) const; + int& operator[](int index);// оператор за индексиране(като в масивите) vector a; a[4] -взима четвъртия кординат на вектора + void print(); +}; + +Vector operator+(const Vector& lhs, const Vector& rhs);// Събиране на два вектора +Vector operator-(const Vector& lhs, const Vector& rhs);// Изваждане на два вектора + +int operator%(const Vector& lhs, const Vector& rhs); // Скаларно произведение на два вектора + +bool operator||(const Vector& lhs, const Vector& rhs); // Дали два вектора са успоредни +bool operator|=(const Vector& lhs, const Vector& rhs); // Дали два вектора са перпендикулярни diff --git a/Templates/Queue.hpp b/Templates/Queue.hpp deleted file mode 100644 index 128f1df..0000000 --- a/Templates/Queue.hpp +++ /dev/null @@ -1,121 +0,0 @@ -#ifndef QUEUE_HDR -#define QUEUE_HDR - -#include -using namespace std; - -template -class Queue { -private: - T * arr; - int capacity; - int count; - - int whereToPut; - int whereToGet; - void Resize(); - void CopyFrom(const Queue& other); - void Free(); - -public: - Queue(); - Queue(const Queue& other); - Queue& operator=(const Queue& other); - ~Queue(); - - bool isEmpty() const; - void Push(T el); - T Pop(); - T& Peek(); -}; - -template -void Queue::Resize() { - T* temp = new T[capacity * 2]; - for (int i = 0; i < capacity; ++i) - temp[i] = Pop(); - whereToGet = 0; - whereToPut = capacity; - count = capacity; - capacity *= 2; - delete[] arr; - arr = temp; -} - -template -void Queue::CopyFrom(const Queue& other) { - arr = new T[other.capacity]; - for (int i = 0; i < other.count; ++i) - arr[i] = other.arr[i]; - count = other.count; - capacity = other.capacity; - whereToPut = other.whereToPut; - whereToGet = other.whereToGet; -} - -template -void Queue::Free() { - delete[] arr; - count = capacity = 0; -} - -template -Queue::Queue() { - arr = new T[4]; - capacity = 4; - count = 0; - whereToPut = 0; - whereToGet = 0; -} - -template -Queue::Queue(const Queue& other) { - CopyFrom(other); -} - -template -Queue& Queue::operator=(const Queue& other) { - if (this != &other) { - Free(); - CopyFrom(other); - } - return *this; -} - -template -Queue::~Queue() { - Free(); -} - -template -bool Queue::isEmpty() const { - return count == 0; -} - -template -void Queue::Push(T el) { - if (count == capacity) - Resize(); - arr[whereToPut] = el; - (whereToPut += 1) %= capacity; - count++; -} - -template -T Queue::Pop() { - if (count == 0) - throw "Queue is empty"; - T elToReturn = arr[whereToGet]; - count--; - (whereToGet += 1) %= capacity; - return elToReturn; -} - -template -T& Queue::Peek() { - if (isEmpty()) - throw std::logic_error("empty queue"); - return arr[whereToGet]; -} - -#endif // !QUEUE_HDR diff --git a/Templates/Queue/Queue.hpp b/Templates/Queue/Queue.hpp new file mode 100644 index 0000000..128f1df --- /dev/null +++ b/Templates/Queue/Queue.hpp @@ -0,0 +1,121 @@ +#ifndef QUEUE_HDR +#define QUEUE_HDR + +#include +using namespace std; + +template +class Queue { +private: + T * arr; + int capacity; + int count; + + int whereToPut; + int whereToGet; + void Resize(); + void CopyFrom(const Queue& other); + void Free(); + +public: + Queue(); + Queue(const Queue& other); + Queue& operator=(const Queue& other); + ~Queue(); + + bool isEmpty() const; + void Push(T el); + T Pop(); + T& Peek(); +}; + +template +void Queue::Resize() { + T* temp = new T[capacity * 2]; + for (int i = 0; i < capacity; ++i) + temp[i] = Pop(); + whereToGet = 0; + whereToPut = capacity; + count = capacity; + capacity *= 2; + delete[] arr; + arr = temp; +} + +template +void Queue::CopyFrom(const Queue& other) { + arr = new T[other.capacity]; + for (int i = 0; i < other.count; ++i) + arr[i] = other.arr[i]; + count = other.count; + capacity = other.capacity; + whereToPut = other.whereToPut; + whereToGet = other.whereToGet; +} + +template +void Queue::Free() { + delete[] arr; + count = capacity = 0; +} + +template +Queue::Queue() { + arr = new T[4]; + capacity = 4; + count = 0; + whereToPut = 0; + whereToGet = 0; +} + +template +Queue::Queue(const Queue& other) { + CopyFrom(other); +} + +template +Queue& Queue::operator=(const Queue& other) { + if (this != &other) { + Free(); + CopyFrom(other); + } + return *this; +} + +template +Queue::~Queue() { + Free(); +} + +template +bool Queue::isEmpty() const { + return count == 0; +} + +template +void Queue::Push(T el) { + if (count == capacity) + Resize(); + arr[whereToPut] = el; + (whereToPut += 1) %= capacity; + count++; +} + +template +T Queue::Pop() { + if (count == 0) + throw "Queue is empty"; + T elToReturn = arr[whereToGet]; + count--; + (whereToGet += 1) %= capacity; + return elToReturn; +} + +template +T& Queue::Peek() { + if (isEmpty()) + throw std::logic_error("empty queue"); + return arr[whereToGet]; +} + +#endif // !QUEUE_HDR diff --git a/Templates/Queue/main.cpp b/Templates/Queue/main.cpp new file mode 100644 index 0000000..89b8468 --- /dev/null +++ b/Templates/Queue/main.cpp @@ -0,0 +1,23 @@ +#include "Queue.hpp" + + +int main() +{ + Queue q; + q.Enqueue(3); + q.Dequeue(); + q.Enqueue(1); + q.Enqueue(2); + q.Enqueue(3); + q.Enqueue(4); + q.Enqueue(5); + q.Enqueue(6); + cout< q; - q.Enqueue(3); - q.Dequeue(); - q.Enqueue(1); - q.Enqueue(2); - q.Enqueue(3); - q.Enqueue(4); - q.Enqueue(5); - q.Enqueue(6); - cout<