diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..efc93080 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -3,5 +3,6 @@ int64_t Addition(int a, int b) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file + + return static_cast(a) + static_cast(b); +} diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index 3a7344d9..ac85f5c8 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -1,7 +1,60 @@ #include #include +size_t CharChanger(char* array, size_t size, char delimiter) { + if (size == 0) return 0; -size_t CharChanger(char array[], size_t size, char delimiter = ' ') { - throw std::runtime_error{"Not implemented"}; -} + size_t writePos = 0; // куда пишем результат + size_t readPos = 0; // откуда читаем исходные символы + + while (readPos < size - 1) { // последний символ — '\0' + char currentChar = array[readPos]; + + // Приведения текущего символа к определенным типам: пробел, число или ASCII символ + bool isSpace = std::isspace(static_cast(currentChar)) != 0; + bool isDigit = std::isdigit(static_cast(currentChar)) != 0; + bool isAlpha = std::isalpha(static_cast(currentChar)) != 0; + + // Подсчёт длины последовательности одинаковых символов + size_t nextPos = readPos + 1; + while (nextPos < size - 1 && array[nextPos] == currentChar) { + nextPos++; + } + size_t runLength = nextPos - readPos; + + // Обработка пробелов + if (isSpace) { + array[writePos++] = delimiter; + } else { + char outChar; + + if (isDigit) { + outChar = '*'; + } else if (isAlpha) { + if (std::islower(static_cast(currentChar))) { + outChar = std::toupper(static_cast(currentChar)); + } else { + outChar = currentChar; // буква и так прописная + } + } else { + outChar = '_'; + } + + array[writePos++] = outChar; + + // Добавление количества повторений + if (runLength > 1) { + if (runLength >= 10) { + array[writePos++] = '0'; + } else { + array[writePos++] = char('0' + runLength); + } + } + } + + readPos = nextPos; + } + + array[writePos] = '\0'; + return writePos; +} \ No newline at end of file diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index 75e7c652..ef3bda88 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -14,5 +14,39 @@ enum class CheckFlags : uint8_t { }; void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; -} + uint8_t value = static_cast(flags); + uint8_t all_bits = static_cast(CheckFlags::ALL); + + // выход за пределы возможных значений + if (value & ~all_bits) { + return; + } + + // не установлено никаких флагов + if (value == 0) { + std::cout << "[]"; + return; + } + + const std::pair flag_names[] = { + {CheckFlags::TIME, "TIME"}, + {CheckFlags::DATE, "DATE"}, + {CheckFlags::USER, "USER"}, + {CheckFlags::CERT, "CERT"}, + {CheckFlags::KEYS, "KEYS"}, + {CheckFlags::DEST, "DEST"} + }; + + bool first = true; + std::cout << "["; + for (const auto& flag : flag_names) { + if (value & static_cast(flag.first)) { + if (!first) { + std::cout << ","; + } + std::cout << flag.second; + first = false; + } + } + std::cout << "]"; +} \ No newline at end of file diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..de9f1a2d 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,68 @@ +constexpr long double FT_TO_M = 0.3048L; +constexpr long double M_TO_FT = 1.0L / FT_TO_M; +constexpr long double FT_TO_IN = 12.0L; +constexpr long double IN_TO_FT = 1.0L / FT_TO_IN; +constexpr long double FT_TO_CM = FT_TO_M * 100.0L; +constexpr long double CM_TO_FT = 1.0L / FT_TO_CM; + +constexpr long double IN_TO_M = 0.0254L; +constexpr long double M_TO_IN = 1.0L / IN_TO_M; +constexpr long double IN_TO_CM = IN_TO_M * 100.0L; +constexpr long double CM_TO_IN = 1.0L / IN_TO_CM; + + +constexpr long double CM_TO_M = 0.01L; +constexpr long double M_TO_CM = 1.0L / CM_TO_M; + + +// ft -> +constexpr double operator"" _ft_to_m(long double value) { + return static_cast(value * FT_TO_M); +} + +constexpr double operator"" _ft_to_in(long double value) { + return static_cast(value * FT_TO_IN); +} + +constexpr double operator"" _ft_to_cm(long double value) { + return static_cast(value * FT_TO_CM); +} + +// in -> +constexpr double operator"" _in_to_m(long double value) { + return static_cast(value * IN_TO_M); +} + +constexpr double operator"" _in_to_ft(long double value) { + return static_cast(value * IN_TO_FT); +} + +constexpr double operator"" _in_to_cm(long double value) { + return static_cast(value * IN_TO_CM); +} + +// cm -> +constexpr double operator"" _cm_to_m(long double value) { + return static_cast(value * CM_TO_M); +} + +constexpr double operator"" _cm_to_ft(long double value) { + return static_cast(value * CM_TO_FT); +} + +constexpr double operator"" _cm_to_in(long double value) { + return static_cast(value * CM_TO_IN); +} + +// m -> +constexpr double operator"" _m_to_ft(long double value) { + return static_cast(value * M_TO_FT); +} + +constexpr double operator"" _m_to_in(long double value) { + return static_cast(value * M_TO_IN); +} + +constexpr double operator"" _m_to_cm(long double value) { + return static_cast(value * M_TO_CM); +} diff --git a/01_week/tasks/print_bits/print_bits.cpp b/01_week/tasks/print_bits/print_bits.cpp index a48a43c1..454e6f2a 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -2,6 +2,31 @@ #include -void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; + void PrintBits(long long value, size_t bytes) { + using std::cout; + using ULL = unsigned long long; + constexpr char BITS_IN_BYTE = 8; + constexpr char BYTES_IN_LONG_LONG = sizeof(long long); + + size_t bits = bytes * BITS_IN_BYTE; + + // Сдвиг, чтобы напечатать младшие байты + ULL mask = (bytes == BYTES_IN_LONG_LONG) + ? ~0ULL + : ((1ULL << (bits)) - 1); + + ULL valueWithMask = static_cast(value) & mask; + cout << "0b"; + + for(size_t i = 0; i < bits; ++i) { + size_t bitIndex = bits - i - 1; + bool bit = (valueWithMask >> bitIndex) & 1; // определение бита на позиции bitIndex + cout << (bit ? '1' : '0'); + + if(bitIndex % 4 == 0 && bitIndex != 0) { + cout << '\''; + } + } + + cout << '\n'; } diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..892d52c6 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,36 @@ #include - +#include +#include +#include void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file + using std::cout, std::setprecision; + if(a == 0 && b == 0 && c == 0) { + cout << "infinite solutions"; + return; + } + if(a == 0 && b == 0 && c != 0) { + cout << "no solutions"; + return; + } + + if(a != 0) { // two roots + int discriminant = b * b - 4 * a * c; + + cout << setprecision(6); + if(discriminant > 0) { + double discriminantRoot = sqrt(discriminant); + double x1 = (-b - discriminantRoot) / (2.0*a); + double x2 = (-b + discriminantRoot) / (2.0*a); + cout << x1 << ' ' << x2; + } else if(discriminant == 0){ + double x1 = (-b) / (2.0*a); + cout << x1; + } else { + cout << "no solutions"; + } + } else { // only one root + double x1 = static_cast(-c) / b; + cout << x1; + } +} diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..c1234590 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,7 +1,16 @@ -#include -#include +#include double CalculateRMS(double values[], size_t size) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file + if(size == 0) return 0.0; + if(values == nullptr) return 0.0; + + long double sumOfSquares = 0; + + for(size_t i = 0; i < size; ++i) { + double &value = values[i]; + sumOfSquares += value * value; + } + + return sqrt(sumOfSquares / size); +} diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index b327e68d..4eefe146 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,16 @@ #include -double ApplyOperations(double a, double b /* other arguments */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +double ApplyOperations(double a, double b, double (**ops)(double, double), size_t size) { + if (ops == nullptr || size == 0) return 0.0; + + double sum = 0.0; + for (size_t i = 0; i < size; ++i) { + if (ops[i] == nullptr) { + continue; // , nullptr + } + sum += ops[i](a, b); + } + + return sum; +} diff --git a/02_week/tasks/last_of_us/last_of_us.cpp b/02_week/tasks/last_of_us/last_of_us.cpp index c7bf1a25..a02b98e3 100644 --- a/02_week/tasks/last_of_us/last_of_us.cpp +++ b/02_week/tasks/last_of_us/last_of_us.cpp @@ -1,6 +1,11 @@ -#include +template +const int* FindLastElement(const int* begin, const int* end, Predicate pred) { + if (begin == nullptr || end == nullptr || begin > end) return end; - -/* return_type */ FindLastElement(/* ptr_type */ begin, /* ptr_type */ end, /* func_type */ predicate) { - throw std::runtime_error{"Not implemented"}; + for (const int* ptr = end - 1; ptr >= begin; --ptr) { + if (pred(*ptr)) { + return ptr; + } + } + return end; } \ No newline at end of file diff --git a/02_week/tasks/little_big/little_big.cpp b/02_week/tasks/little_big/little_big.cpp index abe24379..e0e66469 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,48 @@ -#include +#include +void PrintMemory(int value, bool reverse = false) { + using std::cout, std::hex, std::uppercase, std::setw, std::setfill; + // Представляем как массив байт + const uint8_t* bytes = reinterpret_cast(&value); -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; + cout << "0x"; + cout << uppercase << hex; + if (reverse) { + // Печатаем от старших к младшим + for (int i = sizeof(int) - 1; i >= 0; --i) { + cout << setw(2) + << setfill('0') << static_cast(bytes[i]); + } + } + else { + // Печатаем от младших к старшим + for (size_t i = 0; i < sizeof(int); ++i) { + cout << setw(2) + << setfill('0') << static_cast(bytes[i]); + } + } + cout << "\n"; } -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +void PrintMemory(double value, bool reverse = false) { + using std::cout, std::hex, std::uppercase, std::setw, std::setfill; + const uint8_t* bytes = reinterpret_cast(&value); + + cout << "0x"; + cout << uppercase << hex; + if (reverse) { + // Печатаем от старших к младшим + for (int i = sizeof(double) - 1; i >= 0; --i) { + cout << setw(2) + << setfill('0') << static_cast(bytes[i]); + } + } + else { + // Печатаем от младших к старшим + for (size_t i = 0; i < sizeof(double); ++i) { + cout << setw(2) + << setfill('0') << static_cast(bytes[i]); + } + } + cout << "\n"; +} diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..998f35cc 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,46 @@ -#include +const char* FindLongestSubsequence(const char* begin, const char* end, size_t& count) { + if (!begin || !end || begin >= end) { + count = 0; + return nullptr; + } + const char* longestStringStart = begin; + size_t longestStringLength = 1; + const char* currentStart = begin; + size_t currentLength = 1; + const char* previousCharacter = begin; + const char* currentCharacter = begin + 1; -/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) { - throw std::runtime_error{"Not implemented"}; + for (; currentCharacter < end; ++currentCharacter) { + if (*currentCharacter == *previousCharacter) { + currentLength++; + } + else { + if (currentLength > longestStringLength) { + longestStringLength = currentLength; + longestStringStart = currentStart; + } + currentStart = currentCharacter; + currentLength = 1; + } + previousCharacter = currentCharacter; + } + + // + if (currentLength > longestStringLength) { + longestStringLength = currentLength; + longestStringStart = currentStart; + } + + count = longestStringLength; + return longestStringStart; } + +char* FindLongestSubsequence(char* begin, char* end, size_t& count) { + return const_cast( + FindLongestSubsequence(static_cast(begin), + static_cast(end), + count) + ); +} + diff --git a/02_week/tasks/pretty_array/pretty_array.cpp b/02_week/tasks/pretty_array/pretty_array.cpp index 48eab341..3b026dfa 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,63 @@ -#include +void PrintArray(nullptr_t, nullptr_t, size_t = 0) { + std::cout << "[]\n"; +} +template +void PrintArray(const T* begin, const T* end, size_t limit = 0) { + using std::cout; + if (begin == nullptr || end == nullptr || begin == end) { + cout << "[]\n"; + return; + } -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; + bool reversed = end < begin; + const T* first = begin; + const T* last = end; + + + size_t count = abs(static_cast(last - first)); // + + // + cout << "["; + if (limit == 0 || limit >= count) { + if (reversed == false) { + for (const T* ptr = first; ptr != last; ++ptr) { + if (ptr != first) cout << ", "; + cout << *ptr; + } + } + else { + for (const T* ptr = first; ptr != last; --ptr) { + if (ptr != first) cout << ", "; + cout << *ptr; + } + } + cout << "]\n"; + return; + } + + + // + size_t printed = 0; + const T* ptr = first; + + while (printed < count) { + size_t onLine = 0; + + while (onLine < limit && printed < count) { + if (onLine > 0) cout << ", "; + cout << *ptr; + ++onLine; + ++printed; + ptr += reversed ? -1 : 1; + } + + // , + if (printed < count) { + cout << ", ...\n"; + cout << " "; + } + } + + cout << "]\n"; } \ No newline at end of file diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index 93db625d..782c7a14 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,6 @@ -#include - - -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +template +void SwapPtr(T*& ptr1, T*& ptr2) { + T* tempPtr = ptr1; + ptr1 = ptr2; + ptr2 = tempPtr; } \ No newline at end of file diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index b941c211..67bad12b 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -1,11 +1,29 @@ #include - +#include +#include struct DataStats { double avg = 0.0; double sd = 0.0; }; -/* return_type */ CalculateDataStats(/* args */) { - throw std::runtime_error{"Not implemented"}; -} +DataStats CalculateDataStats(const std::vector& data) { + DataStats stats; + + if (data.empty()) { + return stats; + } + + double sum = 0.0; + double sum_of_squares = 0.0; + for (const int& value : data) { + sum += value; + sum_of_squares += static_cast(value) * value; + } + + stats.avg = sum / data.size(); + double variance = (sum_of_squares / data.size()) - (stats.avg * stats.avg); + variance = variance >= 0.0 ? variance : 0.0; + stats.sd = std::sqrt(variance); + return stats; +} \ No newline at end of file diff --git a/03_week/tasks/easy_compare/easy_compare.cpp b/03_week/tasks/easy_compare/easy_compare.cpp index dd5cb7f6..2ebd4206 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -1,10 +1,12 @@ #include - struct Date { unsigned year; unsigned month; unsigned day; + + Date() : year(0), month(0), day(0) {} + Date(unsigned y, unsigned m, unsigned d) : year(y), month(m), day(d) {} }; struct StudentInfo { @@ -13,4 +15,66 @@ struct StudentInfo { int score; unsigned course; Date birth_date; -}; \ No newline at end of file +}; + +bool operator==(const Date& lhs, const Date& rhs) { + return std::tie(lhs.year, lhs.month, lhs.day) == + std::tie(rhs.year, rhs.month, rhs.day); +} + +bool operator!=(const Date& lhs, const Date& rhs) { + return !(lhs == rhs); +} + +bool operator<(const Date& lhs, const Date& rhs) { + return std::tie(lhs.year, lhs.month, lhs.day) < + std::tie(rhs.year, rhs.month, rhs.day); +} + +bool operator<=(const Date& lhs, const Date& rhs) { + return !(rhs < lhs); +} + +bool operator>(const Date& lhs, const Date& rhs) { + return rhs < lhs; +} + +bool operator>=(const Date& lhs, const Date& rhs) { + return !(lhs < rhs); +} + +bool operator==(const StudentInfo& lhs, const StudentInfo& rhs) { + return lhs.mark == rhs.mark && lhs.score == rhs.score; +} + +bool operator!=(const StudentInfo& lhs, const StudentInfo& rhs) { + return !(lhs == rhs); +} + +bool operator<(const StudentInfo& lhs, const StudentInfo& rhs) { + if (lhs.mark != rhs.mark) { + return lhs.mark > rhs.mark; + } + + if (lhs.score != rhs.score) { + return lhs.score < rhs.score; + } + + if (lhs.course != rhs.course) { + return lhs.course > rhs.course; + } + + return lhs.birth_date < rhs.birth_date; +} + +bool operator<=(const StudentInfo& lhs, const StudentInfo& rhs) { + return !(rhs < lhs); +} + +bool operator>(const StudentInfo& lhs, const StudentInfo& rhs) { + return rhs < lhs; +} + +bool operator>=(const StudentInfo& lhs, const StudentInfo& rhs) { + return !(lhs < rhs); +} \ No newline at end of file diff --git a/03_week/tasks/enum_operators/enum_operators.cpp b/03_week/tasks/enum_operators/enum_operators.cpp index a539be38..0762da8a 100644 --- a/03_week/tasks/enum_operators/enum_operators.cpp +++ b/03_week/tasks/enum_operators/enum_operators.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -12,22 +14,85 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -/* return_type */ operator|(/* args */) { - throw std::runtime_error{"Not implemented"}; +// разрешены только младшие 6 бит +inline CheckFlags sanitize(CheckFlags flags) { + uint8_t value = static_cast(flags); + uint8_t all_value = static_cast(CheckFlags::ALL); + return static_cast(value & all_value); } -/* return_type */ operator&(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator|(CheckFlags lhs, CheckFlags rhs) { + uint8_t result = static_cast(lhs) | static_cast(rhs); + return sanitize(static_cast(result)); } -/* return_type */ operator^(/* args */) { - throw std::runtime_error{"Not implemented"}; +bool operator&(CheckFlags lhs, CheckFlags rhs) { + lhs = sanitize(lhs); + rhs = sanitize(rhs); + + uint8_t lhs_val = static_cast(lhs); + uint8_t rhs_val = static_cast(rhs); + if (lhs_val == 0 || rhs_val == 0) { + return false; + } + + uint8_t common = lhs_val & rhs_val; + return common == lhs_val || common == rhs_val; } -/* return_type */ operator~(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator^(CheckFlags lhs, CheckFlags rhs) { + uint8_t result = static_cast(lhs) ^ static_cast(rhs); + return sanitize(static_cast(result)); } -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator~(CheckFlags flags) { + uint8_t all_value = static_cast(CheckFlags::ALL); + uint8_t value = static_cast(flags); + + uint8_t result = (~value) & all_value; + return static_cast(result); } + +std::ostream& operator<<(std::ostream& os, CheckFlags flags) { + flags = sanitize(flags); + + uint8_t value = static_cast(flags); + if (value == 0) { + os << "NONE"; + return os; + } + + bool first = true; + if (value & static_cast(CheckFlags::TIME)) { + if (!first) os << ", "; + os << "TIME"; + first = false; + } + if (value & static_cast(CheckFlags::DATE)) { + if (!first) os << ", "; + os << "DATE"; + first = false; + } + if (value & static_cast(CheckFlags::USER)) { + if (!first) os << ", "; + os << "USER"; + first = false; + } + if (value & static_cast(CheckFlags::CERT)) { + if (!first) os << ", "; + os << "CERT"; + first = false; + } + if (value & static_cast(CheckFlags::KEYS)) { + if (!first) os << ", "; + os << "KEYS"; + first = false; + } + if (value & static_cast(CheckFlags::DEST)) { + if (!first) os << ", "; + os << "DEST"; + first = false; + } + + return os; +} \ No newline at end of file diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index 6648cb39..65b62934 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -1,6 +1,20 @@ #include +#include +void Filter(std::vector& vec, bool (*predicate)(int)) { + if (predicate == nullptr) { + return; + } -/* return_type */ Filter(/* args */) { - throw std::runtime_error{"Not implemented"}; + size_t write_position = 0; + for (size_t read_position = 0; read_position < vec.size(); ++read_position) { + if (predicate(vec[read_position])) { + if (write_position != read_position) { + vec[write_position] = vec[read_position]; + } + ++write_position; + } + } + + vec.resize(write_position); } \ No newline at end of file diff --git a/03_week/tasks/find_all/find_all.cpp b/03_week/tasks/find_all/find_all.cpp index 74f393b2..65cf5938 100644 --- a/03_week/tasks/find_all/find_all.cpp +++ b/03_week/tasks/find_all/find_all.cpp @@ -1,6 +1,19 @@ -#include +#include +#include +std::vector FindAll(const std::vector& vec, bool (*predicate)(int)) { + if (predicate == nullptr) { + return std::vector(); + } -/* return_type */ FindAll(/* args */) { - throw std::runtime_error{"Not implemented"}; + std::vector result; + for (size_t i = 0; i < vec.size(); ++i) { + if (predicate(vec[i])) { + result.push_back(i); + } + } + + result.shrink_to_fit(); + + return result; } \ No newline at end of file diff --git a/03_week/tasks/minmax/minmax.cpp b/03_week/tasks/minmax/minmax.cpp index c2869799..fc8a913d 100644 --- a/03_week/tasks/minmax/minmax.cpp +++ b/03_week/tasks/minmax/minmax.cpp @@ -1,6 +1,58 @@ #include +#include +#include +std::pair::const_iterator, std::vector::const_iterator> MinMax(const std::vector& vec) { + if (vec.empty()) { + return {vec.end(), vec.end()}; + } -/* return_type */ MinMax(/* args */) { - throw std::runtime_error{"Not implemented"}; -} + if (vec.size() == 1) { + return {vec.begin(), vec.begin()}; + } + + auto min_it = vec.begin(); + auto max_it = vec.begin(); + auto it = vec.begin() + 1; + if (vec.size() % 2 == 0) { + if (*it < *min_it) { + min_it = it; + } else if (*it >= *max_it) { + max_it = it; + } + ++it; + } + + while ((it + 1) < vec.end()) { + auto it1 = it; + auto it2 = it + 1; + + if (*it1 <= *it2) { + if (*it1 < *min_it) { + min_it = it1; + } + if (*it2 >= *max_it) { + max_it = it2; + } + } else { + if (*it2 < *min_it) { + min_it = it2; + } + if (*it1 >= *max_it) { + max_it = it1; + } + } + + it += 2; + } + + if (it != vec.end()) { + if (*it < *min_it) { + min_it = it; + } else if (*it >= *max_it) { + max_it = it; + } + } + + return {min_it, max_it}; +} \ No newline at end of file diff --git a/03_week/tasks/os_overload/os_overload.cpp b/03_week/tasks/os_overload/os_overload.cpp index e473418d..3006ead7 100644 --- a/03_week/tasks/os_overload/os_overload.cpp +++ b/03_week/tasks/os_overload/os_overload.cpp @@ -1,21 +1,59 @@ +#include #include #include #include - struct Coord2D { - int x; - int y; + int x = 0; + int y = 0; + + Coord2D() = default; + Coord2D(int x_val, int y_val) : x(x_val), y(y_val) {} }; struct Circle { - Coord2D coord; - unsigned radius; + Coord2D coord = {0, 0}; + unsigned radius = 1; + + Circle() = default; + Circle(Coord2D c, unsigned r = 1) : coord(c), radius(r) {} }; using CircleRegion = std::pair; using CircleRegionList = std::vector; -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::ostream& operator<<(std::ostream& os, const Coord2D& coord) { + os << "(" << coord.x << ", " << coord.y << ")"; + return os; +} + +std::ostream& operator<<(std::ostream& os, const Circle& circle) { + if (circle.radius == 0) { + os << "circle[]"; + } else { + os << "circle[" << circle.coord << ", r = " << circle.radius << "]"; + } + return os; +} + +std::ostream& operator<<(std::ostream& os, const CircleRegion& region) { + os << (region.second ? "+" : "-") << region.first; + return os; } + +std::ostream& operator<<(std::ostream& os, const CircleRegionList& list) { + if (list.empty()) { + os << "{}"; + } else { + os << "{\n"; + for (size_t i = 0; i < list.size(); ++i) { + os << "\t" << list[i]; + if (i < list.size() - 1) { + os << ","; + } + os << "\n"; + } + os << "}"; + } + return os; +} \ No newline at end of file diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index d2085495..e46e4f1a 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -1,7 +1,28 @@ -#include #include +std::vector Range(int from, int to, int step = 1) { + if (step == 0) { + return std::vector(); + } -std::vector Range(int from, int to, int step) { - throw std::runtime_error{"Not implemented"}; -} + if ((step > 0 && from >= to) || (step < 0 && from <= to)) { + return std::vector(); + } + + int count; + if (step > 0) { + count = (to - from + step - 1) / step; + } else { + count = (to - from + step + 1) / step; + } + + std::vector result; + result.reserve(count); + + bool isForward = step > 0; + for (int i = from; isForward ? (i < to) : (i > to); i += step) { + result.push_back(i); + } + + return result; +} \ No newline at end of file diff --git a/03_week/tasks/unique/unique.cpp b/03_week/tasks/unique/unique.cpp index 9d2545bb..aa039aba 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -1,6 +1,27 @@ #include #include -/* return_type */ Unique(/* args */) { - throw std::runtime_error{"Not implemented"}; -} +std::vector Unique(const std::vector& vec) { + if (vec.empty()) { + return std::vector(); + } + + size_t unique_count = 1; + for (size_t i = 1; i < vec.size(); ++i) { + if (vec[i] != vec[i - 1]) { + ++unique_count; + } + } + + std::vector result; + result.reserve(unique_count); + result.push_back(vec[0]); + + for (size_t i = 1; i < vec.size(); ++i) { + if (vec[i] != vec[i - 1]) { + result.push_back(vec[i]); + } + } + + return result; +} \ No newline at end of file diff --git a/04_week/tasks/phasor/phasor.cpp b/04_week/tasks/phasor/phasor.cpp index 3ec1b9ad..dcc0a7bd 100644 --- a/04_week/tasks/phasor/phasor.cpp +++ b/04_week/tasks/phasor/phasor.cpp @@ -1,10 +1,206 @@ +#include "phasor.hpp" +double Phasor::NormalizePhase(double phase) { + // Используем std::remainder для нормализации в диапазон (-pi, pi] + constexpr double TWO_PI = 2.0 * M_PI; + double normalized = std::remainder(phase, TWO_PI); + // std::remainder возвращает значение [-pi, pi] + if (normalized <= -M_PI) { + normalized += TWO_PI; + } + return normalized; +} -struct ExpTag {}; -struct DegTag {}; -struct AlgTag {}; +Phasor::Phasor() : real_(0.0), imag_(0.0) {} +Phasor::Phasor(double magnitude, double phase) { + // Если амплитуда отрицательная, делаем её положительной и сдвигаем фазу на pi + if (magnitude < 0) { + magnitude = -magnitude; + phase += M_PI; + } + phase = NormalizePhase(phase); + real_ = magnitude * std::cos(phase); + imag_ = magnitude * std::sin(phase); +} -class Phasor { +Phasor::Phasor(double magnitude, double phase, ExpTag) : Phasor(magnitude, phase) {} -}; +Phasor::Phasor(double magnitude, double phase_deg, DegTag) + : Phasor(magnitude, phase_deg * M_PI / 180.0) {} + +Phasor::Phasor(double real, double imag, AlgTag) : real_(real), imag_(imag) {} + +void Phasor::SetPolar(double magnitude, double phase) { + if (magnitude < 0) { + magnitude = -magnitude; + phase += M_PI; + } + phase = NormalizePhase(phase); + real_ = magnitude * std::cos(phase); + imag_ = magnitude * std::sin(phase); +} + +void Phasor::SetCartesian(double real, double imag) { + real_ = real; + imag_ = imag; +} + +double Phasor::Magnitude() const { + return std::hypot(real_, imag_); +} + +double Phasor::Phase() const { + return std::atan2(imag_, real_); +} + +double Phasor::PhaseDeg() const { + return Phase() * 180.0 / M_PI; +} + +double Phasor::Real() const { + return real_; +} + +double Phasor::Imag() const { + return imag_; +} + +double Phasor::Abs() const { + return Magnitude(); +} + +double Phasor::Angle() const { + return Phase(); +} + +double Phasor::AngleDeg() const { + return PhaseDeg(); +} + +Phasor Phasor::Conj() const { + return Phasor(real_, -imag_, AlgTag{}); +} + +Phasor Phasor::Inv() const { + double mag_sq = real_ * real_ + imag_ * imag_; + return Phasor(real_ / mag_sq, -imag_ / mag_sq, AlgTag{}); +} + +Phasor Phasor::operator-() const { + return Phasor(-real_, -imag_, AlgTag{}); +} + +Phasor& Phasor::operator+=(const Phasor& other) { + real_ += other.real_; + imag_ += other.imag_; + return *this; +} + +Phasor& Phasor::operator-=(const Phasor& other) { + real_ -= other.real_; + imag_ -= other.imag_; + return *this; +} + +Phasor& Phasor::operator*=(const Phasor& other) { + double new_real = real_ * other.real_ - imag_ * other.imag_; + double new_imag = real_ * other.imag_ + imag_ * other.real_; + real_ = new_real; + imag_ = new_imag; + return *this; +} + +Phasor& Phasor::operator/=(const Phasor& other) { + double denom = other.real_ * other.real_ + other.imag_ * other.imag_; + double new_real = (real_ * other.real_ + imag_ * other.imag_) / denom; + double new_imag = (imag_ * other.real_ - real_ * other.imag_) / denom; + real_ = new_real; + imag_ = new_imag; + return *this; +} + +bool Phasor::operator==(const Phasor& other) const { + constexpr double EPSILON = 1e-9; + return std::abs(real_ - other.real_) < EPSILON && + std::abs(imag_ - other.imag_) < EPSILON; +} + +bool Phasor::operator!=(const Phasor& other) const { + return !(*this == other); +} + +Phasor operator+(const Phasor& lhs, const Phasor& rhs) { + return Phasor(lhs.Real() + rhs.Real(), lhs.Imag() + rhs.Imag(), AlgTag{}); +} + +Phasor operator-(const Phasor& lhs, const Phasor& rhs) { + return Phasor(lhs.Real() - rhs.Real(), lhs.Imag() - rhs.Imag(), AlgTag{}); +} + +Phasor operator*(const Phasor& lhs, const Phasor& rhs) { + double real = lhs.Real() * rhs.Real() - lhs.Imag() * rhs.Imag(); + double imag = lhs.Real() * rhs.Imag() + lhs.Imag() * rhs.Real(); + return Phasor(real, imag, AlgTag{}); +} + +Phasor operator/(const Phasor& lhs, const Phasor& rhs) { + double denom = rhs.Real() * rhs.Real() + rhs.Imag() * rhs.Imag(); + double real = (lhs.Real() * rhs.Real() + lhs.Imag() * rhs.Imag()) / denom; + double imag = (lhs.Imag() * rhs.Real() - lhs.Real() * rhs.Imag()) / denom; + return Phasor(real, imag, AlgTag{}); +} + +Phasor operator+(const Phasor& phasor, double scalar) { + return Phasor(phasor.Real() + scalar, phasor.Imag(), AlgTag{}); +} + +Phasor operator+(double scalar, const Phasor& phasor) { + return phasor + scalar; +} + +Phasor operator-(const Phasor& phasor, double scalar) { + return Phasor(phasor.Real() - scalar, phasor.Imag(), AlgTag{}); +} + +Phasor operator-(double scalar, const Phasor& phasor) { + return Phasor(scalar - phasor.Real(), -phasor.Imag(), AlgTag{}); +} + +Phasor operator*(const Phasor& phasor, double scalar) { + return Phasor(phasor.Real() * scalar, phasor.Imag() * scalar, AlgTag{}); +} + +Phasor operator*(double scalar, const Phasor& phasor) { + return phasor * scalar; +} + +Phasor operator/(const Phasor& phasor, double scalar) { + return Phasor(phasor.Real() / scalar, phasor.Imag() / scalar, AlgTag{}); +} + +Phasor operator/(double scalar, const Phasor& phasor) { + double denom = phasor.Real() * phasor.Real() + phasor.Imag() * phasor.Imag(); + double real = (scalar * phasor.Real()) / denom; + double imag = (-scalar * phasor.Imag()) / denom; + return Phasor(real, imag, AlgTag{}); +} + +Phasor MakePhasorCartesian(double real, double imag) { + return Phasor(real, imag, AlgTag{}); +} + +Phasor MakePhasorPolar(double magnitude, double phase) { + return Phasor(magnitude, phase); +} + +Phasor MakePhasorPolarDeg(double magnitude, double phase_deg) { + return Phasor(magnitude, phase_deg, DegTag{}); +} + +std::ostream& operator<<(std::ostream& os, const Phasor& p) { + os << std::fixed << std::setprecision(3); + os << p.Magnitude() << "*e(j*" << p.PhaseDeg() << ") ["; + os << p.Real() << " + j*" << p.Imag() << "]"; + return os; +} \ No newline at end of file diff --git a/04_week/tasks/phasor/phasor.hpp b/04_week/tasks/phasor/phasor.hpp new file mode 100644 index 00000000..16d20326 --- /dev/null +++ b/04_week/tasks/phasor/phasor.hpp @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include + +struct ExpTag {}; +struct DegTag {}; +struct AlgTag {}; + +class Phasor { +private: + double real_ = 0.0; + double imag_ = 0.0; + + // Нормализация фазы + static double NormalizePhase(double phase); + +public: + Phasor(); + Phasor(double magnitude, double phase); + Phasor(double magnitude, double phase, ExpTag); + Phasor(double magnitude, double phase_deg, DegTag); + Phasor(double real, double imag, AlgTag); + + void SetPolar(double magnitude, double phase); + void SetCartesian(double real, double imag); + + double Magnitude() const; + double Phase() const; + double PhaseDeg() const; + + double Real() const; + double Imag() const; + + double Abs() const; + double Angle() const; + double AngleDeg() const; + + Phasor Conj() const; + Phasor Inv() const; + + Phasor operator-() const; + Phasor& operator+=(const Phasor& other); + Phasor& operator-=(const Phasor& other); + Phasor& operator*=(const Phasor& other); + Phasor& operator/=(const Phasor& other); + + bool operator==(const Phasor& other) const; + bool operator!=(const Phasor& other) const; +}; + +Phasor operator+(const Phasor& lhs, const Phasor& rhs); +Phasor operator-(const Phasor& lhs, const Phasor& rhs); +Phasor operator*(const Phasor& lhs, const Phasor& rhs); +Phasor operator/(const Phasor& lhs, const Phasor& rhs); + +Phasor operator+(const Phasor& phasor, double scalar); +Phasor operator+(double scalar, const Phasor& phasor); +Phasor operator-(const Phasor& phasor, double scalar); +Phasor operator-(double scalar, const Phasor& phasor); +Phasor operator*(const Phasor& phasor, double scalar); +Phasor operator*(double scalar, const Phasor& phasor); +Phasor operator/(const Phasor& phasor, double scalar); +Phasor operator/(double scalar, const Phasor& phasor); + +Phasor MakePhasorCartesian(double real, double imag); +Phasor MakePhasorPolar(double magnitude, double phase); +Phasor MakePhasorPolarDeg(double magnitude, double phase_deg); + +std::ostream& operator<<(std::ostream& os, const Phasor& p); diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 2a9f8493..cc0e007b 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,6 +1,122 @@ -#include +#include "queue.hpp" +void Queue::TransferIfNeeded() const { + if (output_stack_.empty() && input_stack_.empty() == false) { + while (input_stack_.empty() == false) { + output_stack_.push_back(input_stack_.back()); + input_stack_.pop_back(); + } + } +} -class Queue { +Queue::Queue(size_t capacity) { + input_stack_.reserve(capacity); +} -}; +Queue::Queue(const std::vector& vec) { + input_stack_ = vec; +} + +Queue::Queue(std::stack s) { + std::vector temp; + temp.reserve(s.size()); + while (s.empty() == false) { + temp.push_back(s.top()); + s.pop(); + } + std::reverse(temp.begin(), temp.end()); + input_stack_ = std::move(temp); +} + +Queue::Queue(std::initializer_list init) { + input_stack_.assign(init.begin(), init.end()); +} + +void Queue::Push(int value) { + input_stack_.push_back(value); +} + +bool Queue::Pop() { + TransferIfNeeded(); + if (output_stack_.empty()) { + return false; + } + output_stack_.pop_back(); + return true; +} + +int& Queue::Front() { + TransferIfNeeded(); + if (output_stack_.empty()) { + return dummy_; + } + return output_stack_.back(); +} + +const int& Queue::Front() const { + TransferIfNeeded(); + if (output_stack_.empty()) { + return dummy_; + } + return output_stack_.back(); +} + +int& Queue::Back() { + if (input_stack_.empty() == false) { + return input_stack_.back(); + } + if (output_stack_.empty() == false) { + return output_stack_.front(); + } + return dummy_; +} + +const int& Queue::Back() const { + if (input_stack_.empty() == false) { + return input_stack_.back(); + } + if (output_stack_.empty() == false) { + return output_stack_.front(); + } + return dummy_; +} + +bool Queue::Empty() const { + return input_stack_.empty() && output_stack_.empty(); +} + +size_t Queue::Size() const { + return input_stack_.size() + output_stack_.size(); +} + +void Queue::Clear() { + input_stack_.clear(); + output_stack_.clear(); +} + +void Queue::Swap(Queue& other) { + input_stack_.swap(other.input_stack_); + output_stack_.swap(other.output_stack_); +} + +bool Queue::operator==(const Queue& other) const { + if (Size() != other.Size()) { + return false; + } + + Queue a = *this; + Queue b = other; + + while (a.Empty() == false) { + if (a.Front() != b.Front()) { + return false; + } + a.Pop(); + b.Pop(); + } + return true; +} + +bool Queue::operator!=(const Queue& other) const { + return (*this == other) == false; +} \ No newline at end of file diff --git a/04_week/tasks/queue/queue.hpp b/04_week/tasks/queue/queue.hpp new file mode 100644 index 00000000..ae2fde4a --- /dev/null +++ b/04_week/tasks/queue/queue.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include +#include +#include + +class Queue { +private: + mutable std::vector input_stack_; + mutable std::vector output_stack_; + mutable int dummy_ = 0; + + void TransferIfNeeded() const; + +public: + Queue() = default; + + explicit Queue(size_t capacity); + explicit Queue(const std::vector& vec); + explicit Queue(std::stack s); + Queue(std::initializer_list init); + + void Push(int value); + bool Pop(); + int& Front(); + const int& Front() const; + int& Back(); + const int& Back() const; + bool Empty() const; + size_t Size() const; + void Clear(); + void Swap(Queue& other); + + bool operator==(const Queue& other) const; + bool operator!=(const Queue& other) const; +}; \ No newline at end of file diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index e2b57ba2..a5fd04c8 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -1,6 +1,176 @@ -#include +#include "ring_buffer.hpp" +#include +size_t RingBuffer::CalculateIndex(size_t logical_index) const { + return (tail_ + logical_index) % capacity_; +} -class RingBuffer { +RingBuffer::RingBuffer(size_t capacity) + : capacity_(capacity == 0 ? 1 : capacity) + , size_(0) + , head_(0) + , tail_(0) { + data_.resize(capacity_); +} -}; +RingBuffer::RingBuffer(size_t capacity, int value) + : capacity_(capacity == 0 ? 1 : capacity) + , size_(capacity_) + , head_(0) + , tail_(0) { + data_.resize(capacity_, value); +} + +RingBuffer::RingBuffer(std::initializer_list init) + : capacity_(init.size() == 0 ? 1 : init.size()) + , size_(init.size()) + , head_(0) + , tail_(0) { + data_.resize(capacity_); + size_t idx = 0; + for (int value : init) { + data_[idx++] = value; + } +} + +RingBuffer::RingBuffer(const RingBuffer& other) + : data_(other.data_) + , capacity_(other.capacity_) + , size_(other.size_) + , head_(other.head_) + , tail_(other.tail_) { +} + +RingBuffer& RingBuffer::operator=(const RingBuffer& other) { + if (this != &other) { + data_ = other.data_; + capacity_ = other.capacity_; + size_ = other.size_; + head_ = other.head_; + tail_ = other.tail_; + } + return *this; +} + +void RingBuffer::Push(int value) { + data_[head_] = value; + head_ = (head_ + 1) % capacity_; + + if (size_ < capacity_) { + ++size_; + } else { + tail_ = (tail_ + 1) % capacity_; + } +} + +bool RingBuffer::TryPush(int value) { + if (Full()) { + return false; + } + Push(value); + return true; +} + +void RingBuffer::Pop() { + if (Empty()) { + return; + } + tail_ = (tail_ + 1) % capacity_; + --size_; +} + +bool RingBuffer::TryPop(int& value) { + if (Empty()) { + return false; + } + value = data_[tail_]; + Pop(); + return true; +} + +int& RingBuffer::operator[](size_t index) { + return data_[CalculateIndex(index)]; +} + +const int& RingBuffer::operator[](size_t index) const { + return data_[CalculateIndex(index)]; +} + +int& RingBuffer::Front() { + size_t front_idx = (head_ + capacity_ - 1) % capacity_; + return data_[front_idx]; +} + +const int& RingBuffer::Front() const { + size_t front_idx = (head_ + capacity_ - 1) % capacity_; + return data_[front_idx]; +} + +int& RingBuffer::Back() { + return data_[tail_]; +} + +const int& RingBuffer::Back() const { + return data_[tail_]; +} + +bool RingBuffer::Empty() const { + return size_ == 0; +} + +bool RingBuffer::Full() const { + return size_ == capacity_; +} + +size_t RingBuffer::Size() const { + return size_; +} + +size_t RingBuffer::Capacity() const { + return capacity_; +} + +void RingBuffer::Clear() { + size_ = 0; + head_ = 0; + tail_ = 0; +} + +void RingBuffer::Resize(size_t new_capacity) { + if (new_capacity == 0) { + new_capacity = 1; + } + + if (new_capacity == capacity_) { + return; + } + + std::vector new_data(new_capacity); + size_t new_size = std::min(size_, new_capacity); + + size_t start_offset = 0; + if (size_ > new_capacity) { + start_offset = size_ - new_capacity; + } + + for (size_t i = 0; i < new_size; ++i) { + new_data[i] = data_[CalculateIndex(start_offset + i)]; + } + + data_ = std::move(new_data); + capacity_ = new_capacity; + size_ = new_size; + tail_ = 0; + head_ = new_size % capacity_; +} + +std::vector RingBuffer::Vector() const { + std::vector result; + result.reserve(size_); + + for (size_t i = 0; i < size_; ++i) { + result.push_back(data_[CalculateIndex(i)]); + } + + return result; +} \ No newline at end of file diff --git a/04_week/tasks/ring_buffer/ring_buffer.hpp b/04_week/tasks/ring_buffer/ring_buffer.hpp new file mode 100644 index 00000000..d5ce435a --- /dev/null +++ b/04_week/tasks/ring_buffer/ring_buffer.hpp @@ -0,0 +1,47 @@ +#pragma once + +#include +#include + +class RingBuffer { +private: + std::vector data_; + size_t capacity_ = 0; + size_t size_ = 0; + size_t head_ = 0; // индекс для добавления (Front) + size_t tail_ = 0; // индекс для удаления (Back) + + // Метод для получения индекса + size_t CalculateIndex(size_t logical_index) const; + +public: + explicit RingBuffer(size_t capacity); + RingBuffer(size_t capacity, int value); + RingBuffer(std::initializer_list init); + RingBuffer(const RingBuffer& other); + + void Push(int value); + bool TryPush(int value); + + void Pop(); + bool TryPop(int& value); + + int& Front(); + const int& Front() const; + + int& Back(); + const int& Back() const; + + bool Empty() const; + bool Full() const; + size_t Size() const; + size_t Capacity() const; + void Clear(); + void Resize(size_t new_capacity); + std::vector Vector() const; + + int& operator[](size_t index); + const int& operator[](size_t index) const; + RingBuffer& operator=(const RingBuffer& other); + +}; \ No newline at end of file diff --git a/04_week/tasks/stack/stack.cpp b/04_week/tasks/stack/stack.cpp index 222e4ffc..ea9ee193 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -1,6 +1,53 @@ -#include +#include "stack.hpp" +void Stack::Push(int value) { + data_.push_back(value); +} -class Stack { +bool Stack::Pop() { + if (data_.empty()) { + return false; + } + data_.pop_back(); + return true; +} -}; +int& Stack::Top() { + if (data_.empty()) { + static int dummy = 0; + return dummy; + } + return data_.back(); +} + +const int& Stack::Top() const { + if (data_.empty()) { + static constexpr int dummy = 0; + return dummy; + } + return data_.back(); +} + +bool Stack::Empty() const { + return data_.empty(); +} + +size_t Stack::Size() const { + return data_.size(); +} + +void Stack::Clear() { + data_.clear(); +} + +void Stack::Swap(Stack& other) { + data_.swap(other.data_); +} + +bool Stack::operator==(const Stack& other) const { + return data_ == other.data_; +} + +bool Stack::operator!=(const Stack& other) const { + return data_ != other.data_; +} \ No newline at end of file diff --git a/04_week/tasks/stack/stack.hpp b/04_week/tasks/stack/stack.hpp new file mode 100644 index 00000000..16c5f949 --- /dev/null +++ b/04_week/tasks/stack/stack.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include + +class Stack { +private: + std::vector data_; + +public: + void Push(int value); + + // Возвращает true если операция выполнена, false если стек пуст + bool Pop(); + + int& Top(); + const int& Top() const; + + bool Empty() const; + size_t Size() const; + void Clear(); + void Swap(Stack& other); + + bool operator==(const Stack& other) const; + bool operator!=(const Stack& other) const; +}; \ No newline at end of file