From 7154dec118ff52f21f02e22ba7eab1fb2a80ce16 Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 21 Nov 2025 17:19:07 +0500 Subject: [PATCH 01/49] add (solution): add addition task --- .gitignore | 2 ++ 01_week/tasks/addition/addition.cpp | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..cec5a363 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/build +/build-asan diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..cf0b78cf 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -3,5 +3,5 @@ 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); +} From 4141f23ff6a9c850cd2933433e37ee5110dec93c Mon Sep 17 00:00:00 2001 From: Radiy Date: Mon, 24 Nov 2025 18:26:38 +0500 Subject: [PATCH 02/49] wip (solution): wip char_changer task --- 01_week/tasks/char_changer/char_changer.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index 3a7344d9..fef06932 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -3,5 +3,14 @@ size_t CharChanger(char array[], size_t size, char delimiter = ' ') { + size_t convertedSymbol = 0; currentSybmol + + for (size_t i = 0; i < size; ++i) { + if (!isalpha(array[])) { + + } + } + + throw std::runtime_error{"Not implemented"}; } From 16fe4e3cf5026c292170c7d31ab7f35aaf2114ad Mon Sep 17 00:00:00 2001 From: Radiy Date: Tue, 25 Nov 2025 18:01:54 +0500 Subject: [PATCH 03/49] add (solution): add char_changer task --- 01_week/tasks/char_changer/char_changer.cpp | 77 +++++++++++++++++++-- 1 file changed, 72 insertions(+), 5 deletions(-) diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index fef06932..bb92525d 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -1,16 +1,83 @@ #include #include +// Есть ощущение, что это можно решить как-то более лаконично и просто + +/** + * @brief Получить длину последовательности из одинаковых знаков. + * @param array указатель на элемент массива, с которого начнется проверка. + * @return Длина последовательности. + * @note Все символы будут сравниваться с первым из переданного массива. + */ +size_t GetIdenticalCharSequenceLen(char *array) { + size_t sequenceLen = 0; + + if (array[0] == '\0') { + return 0; + } + + while (array[0] == array[sequenceLen]) { + ++sequenceLen; + } + + return sequenceLen; +} + +/** + * @brief Сконвертировать одинаковые символы. + * @param array указатель на начало обрабатываемого массива. + * @param convertedSymIdx ссылка на индекс последнего сконвертированного символа. + * @param currentSymIdx ссылка на индекс текущего обрабатываемого символа. + * @param swapChar знак, на который будет произведена замена array[convertedSymIdx]. + * @return none + */ +void ConvertIdenticalCharacters(char array[], size_t& convertedSymIdx, size_t& currentSymIdx, char swapChar) { + size_t sequenceLen = GetIdenticalCharSequenceLen(&array[currentSymIdx]); + + array[convertedSymIdx++] = swapChar; + + if (sequenceLen == 1) { + currentSymIdx += sequenceLen; + return; + } + + if (sequenceLen >= 10) { + array[convertedSymIdx++] = '0'; + } else { + array[convertedSymIdx++] = sequenceLen + '0'; + } + + currentSymIdx += sequenceLen; +} size_t CharChanger(char array[], size_t size, char delimiter = ' ') { - size_t convertedSymbol = 0; currentSybmol + size_t convertedSymbolIdx = 0, currentSymbolIdx = 0; + + while(currentSymbolIdx < size && convertedSymbolIdx < size) { + if (array[currentSymbolIdx] == '\0') { + break; + } - for (size_t i = 0; i < size; ++i) { - if (!isalpha(array[])) { + if (isspace(array[currentSymbolIdx])) { + currentSymbolIdx += GetIdenticalCharSequenceLen(&array[currentSymbolIdx]); + + array[convertedSymbolIdx++] = delimiter; + continue; + } + + if (isalnum(array[currentSymbolIdx])) { + if (isdigit(array[currentSymbolIdx])) { + ConvertIdenticalCharacters(array, convertedSymbolIdx, currentSymbolIdx, '*'); + continue; + } + ConvertIdenticalCharacters(array, convertedSymbolIdx, currentSymbolIdx, toupper(array[currentSymbolIdx])); + continue; } - } + ConvertIdenticalCharacters(array, convertedSymbolIdx, currentSymbolIdx, '_'); + } - throw std::runtime_error{"Not implemented"}; + array[convertedSymbolIdx] = '\0'; + return convertedSymbolIdx; } From e6233b86c16e514cbdaa67dee96b644f777ec869 Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 26 Nov 2025 11:57:47 +0500 Subject: [PATCH 04/49] add (solution): add check_flags task --- 01_week/tasks/check_flags/check_flags.cpp | 45 ++++++++++++++++++++++- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index 75e7c652..a9a5f1f0 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -1,6 +1,6 @@ #include #include - +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -13,6 +13,47 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; +// В данном случае можно было использовать map, но с ним придется использовать +// static_cast. Так же map отсортирует значения по возрасанию, соответственно +// использовать enum написанный иначе будет невозможно. +const std::vector> checkNames = { + {CheckFlags::TIME, "TIME"}, + {CheckFlags::DATE, "DATE"}, + {CheckFlags::USER, "USER"}, + {CheckFlags::CERT, "CERT"}, + {CheckFlags::KEYS, "KEYS"}, + {CheckFlags::DEST, "DEST"}, +}; + void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; + if (flags > CheckFlags::ALL) { + return; + } + + std::string needed_checks = "["; + + if (flags == CheckFlags::NONE) { + needed_checks += "]"; // Такая модификация происходит inplace, не + // создавая дорогостоящие копии + std::cout << needed_checks; + return; + } + + bool first = true; + for (const auto& [key, val] : checkNames) { + if (static_cast(flags) & static_cast(key)) { + if (!first) { + needed_checks += ","; // добавляем запятую перед элементом, а не после, + // проверяя на первый элемент, это гарантирует, что лишних + // запятых не будет + } + + needed_checks += val; + first = false; + } + } + + needed_checks += "]"; + + std::cout << needed_checks; } From 520f1f21379097428f059ecf8d1b40cfc2b7a325 Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 26 Nov 2025 17:04:16 +0500 Subject: [PATCH 05/49] add (solution): add length_lit task --- 01_week/tasks/length_lit/length_lit.cpp | 51 +++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..a5bfb87c 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,51 @@ +constexpr long double METER_IN_FOOT = 0.3048; +constexpr long double INCH_IN_FOOT = 12; +constexpr long double METER_IN_INCH = 0.0254; + +constexpr long double operator""_ft_to_m(long double foot) { + return foot * METER_IN_FOOT; +} + +constexpr long double operator""_m_to_ft(long double meter) { + return meter / METER_IN_FOOT; +} + +constexpr long double operator""_ft_to_cm(long double foot) { + return foot * METER_IN_FOOT * 100; +} + +constexpr long double operator""_cm_to_ft(long double cm) { + return cm / (METER_IN_FOOT * 100); +} + +constexpr long double operator""_ft_to_in(long double foot) { + return foot * INCH_IN_FOOT; +} + +constexpr long double operator""_in_to_ft(long double inch) { + return inch / INCH_IN_FOOT; +} + +constexpr long double operator""_in_to_m(long double inch) { + return inch * METER_IN_INCH; +} + +constexpr long double operator""_m_to_in(long double meter) { + return meter / METER_IN_INCH; +} + +constexpr long double operator""_in_to_cm(long double inch) { + return inch * METER_IN_INCH * 100; +} + +constexpr long double operator""_cm_to_in(long double inch) { + return inch / (METER_IN_INCH * 100); +} + +constexpr long double operator""_m_to_cm(long double meter) { + return meter * 100; +} + +constexpr long double operator""_cm_to_m(long double cm) { + return cm / 100; +} From 057cea08900b18fc14fa4817032f33437ac647df Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 27 Nov 2025 14:39:30 +0500 Subject: [PATCH 06/49] add (solution): add print_bits task --- 01_week/tasks/print_bits/print_bits.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/01_week/tasks/print_bits/print_bits.cpp b/01_week/tasks/print_bits/print_bits.cpp index a48a43c1..3db2d6ab 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -1,7 +1,17 @@ #include #include - +#include void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; + std::string byteForm = "0b"; + // i < bytes * 8 сработает, потому что 0ULL - 1 переполняется в ULL_MAX + for (size_t i = (bytes * 8 - 1); i < bytes * 8; --i) { + byteForm += ((value >> i) & 0x01U) + '0'; + + if (i != 0 && i % 4 == 0) { + byteForm += "'"; + } + } + + std::cout << byteForm << std::endl; } From 5af29501a016fb7a69ca33d08cfbe63bdabd1c94 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 27 Nov 2025 16:05:30 +0500 Subject: [PATCH 07/49] add (solution): add rms task --- 01_week/tasks/quadratic/quadratic.cpp | 64 +++++++++++++++++++++++++-- 01_week/tasks/rms/rms.cpp | 17 +++++-- 2 files changed, 74 insertions(+), 7 deletions(-) diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..9d3d58ba 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,64 @@ #include +#include +#include +// Уверен, что это можно сделать значительно качественнее, но дедлайн близко, +// поэтому спагетти код >:) -void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +void SolveQuadratic(int a, int b, int c) { + if (!a && !b && !c) { + std::cout << "infinite solutions"; + return; + } + + if (!a && !b) { + std::cout << "no solutions"; + return; + } + + std::cout << std::setprecision(6); + + if (!a) { + std::cout << (static_cast(-c) / b); + return; + } + + if (!b) { + if (static_cast(-c) / a < 0) { + std::cout << "no solutions"; + return; + } + + double root = std::sqrt(static_cast(-c) / a); + + if (root == 0) { + std::cout << root; + } else { + std::cout << -root << " " << root; + } + + return; + } + + double d = static_cast(b) * b - 4.0 * a * c; + double x1 = 0.0, x2 = 0.0; + + if (d < 0) { + std::cout << "no solutions"; + return; + } + + if (d > 0) { + x1 = ((-b - std::sqrt(d)) / (2.0 * a)); + x2 = ((-b + std::sqrt(d)) / (2.0 * a)); + + if (x1 > x2) { + std::cout << x2 << " " << x1; + } else { + std::cout << x1 << " " << x2; + } + return; + } + + std::cout << -b / (2.0 * a); +} diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..64cf032f 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,7 +1,16 @@ -#include +#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 || values == NULL) { + return 0.0; + } + + double sum = 0.0; + for (size_t i = 0; i < size; ++i) { + sum += values[i] * values[i]; + } + + return std::sqrt(sum / static_cast(size)); +} From 706b6093330a8d2381f9dff61c22e273a525eb5d Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 5 Dec 2025 17:00:05 +0500 Subject: [PATCH 08/49] add (solution): add swap_ptr task --- 02_week/tasks/swap_ptr/swap_ptr.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index 93db625d..ffaf09dc 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,21 @@ #include +template +void SwapPtr(T &ptr1, T &ptr2) { + T tmp = ptr1; + ptr1 = ptr2; + ptr2 = tmp; +} -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +// Можно сделать перегрузкой, но мы же любим компактность :) +//void SwapPtr(const int* &ptr1, const int* &ptr2) { +// const int* tmp = ptr1; +// ptr1 = ptr2; +// ptr2 = tmp; +//} + +//void SwapPtr(int** &ptr1, int** &ptr2) { +// int** tmp = ptr1; +// ptr1 = ptr2; +// ptr2 = tmp; +//} From 6d51ad2a5cf8d376590e7536ef9680128391fe89 Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 5 Dec 2025 17:33:41 +0500 Subject: [PATCH 09/49] add (solution): add last_of_us task --- 02_week/tasks/last_of_us/last_of_us.cpp | 26 ++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) 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..fa59bff9 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,26 @@ #include +typedef bool (*predicate_func_t)(int); -/* return_type */ FindLastElement(/* ptr_type */ begin, /* ptr_type */ end, /* func_type */ predicate) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +const int* FindLastElement(const int* begin, const int* end, predicate_func_t predicate) { + if (begin == nullptr || end == nullptr) { + return end; + } + + if (begin >= end) { + return end; + } + + const int* result = end; + + // begin и end передаются by copy, так что инкремент указателя + // не повлияет на переданный указатель + while (begin != end) { + if (predicate(*begin)) { + result = begin; + } + ++begin; + } + + return result; +} From 6a457164378f774241a97aec331365782bf097f0 Mon Sep 17 00:00:00 2001 From: Radiy Date: Sat, 6 Dec 2025 15:34:39 +0500 Subject: [PATCH 10/49] add (solution): add func_array task --- 02_week/tasks/func_array/func_array.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index b327e68d..68b25cef 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,19 @@ #include +typedef double(*operations_t)(double, double); -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, operations_t mathOperations[], size_t size) { + if (size == 0 || mathOperations == nullptr) { + return 0.0; + } + + double sum = 0.0; + + for (size_t i = 0; i < size; ++i) { + if (mathOperations[i] != nullptr) { + sum += mathOperations[i](a, b); + } + } + + return sum; +} From 3febd0641b6d4e05a55ad4f32d760951101816fe Mon Sep 17 00:00:00 2001 From: Radiy Date: Sat, 6 Dec 2025 16:28:16 +0500 Subject: [PATCH 11/49] add (solution): add longest task --- 02_week/tasks/longest/longest.cpp | 41 +++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..12b87b36 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,43 @@ #include -/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) { - throw std::runtime_error{"Not implemented"}; +const char* FindLongestSubsequence(const char* begin, const char* end, size_t& count) { + if (begin == nullptr || end == nullptr) { + count = 0; + return nullptr; + } + + if (begin >= end) { + count = 0; + return nullptr; + } + + size_t currSequenseLen = 0; + const char* longestSequenceStart = begin; + + while (begin != end) { + currSequenseLen++; + + if (*begin != *(begin + 1)) { + if (currSequenseLen > count) { + count = currSequenseLen; + longestSequenceStart = begin - (currSequenseLen - 1); + } + currSequenseLen = 0; + } + + ++begin; + } + + return longestSequenceStart; +} + +char* FindLongestSubsequence(char* begin, char* end, size_t& count) { + const char* result = FindLongestSubsequence( + static_cast(begin), + static_cast(end), + count + ); + + return const_cast(result); } From cc1236417d6faa77199514336d3a2fc9d5cee6f5 Mon Sep 17 00:00:00 2001 From: Radiy Date: Mon, 8 Dec 2025 15:11:37 +0500 Subject: [PATCH 12/49] add (solution): add little_big task --- 02_week/tasks/little_big/little_big.cpp | 33 +++++++++++++++++++------ 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/02_week/tasks/little_big/little_big.cpp b/02_week/tasks/little_big/little_big.cpp index abe24379..2506fe16 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,29 @@ -#include +#include +#include +template +void PrintMemory(T num, bool isReversed = false) { + std::string output = ""; -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; -} + // Надеюсь использование memcpy разрешено + unsigned char bytes[sizeof(T)]; + std::memcpy(bytes, &num, sizeof(T)); + + size_t start = isReversed ? (sizeof(T) - 1) : 0; + int step = isReversed ? -1 : 1; + + for (size_t i = start; i < sizeof(T); i += step) { + unsigned char currentByte = bytes[i]; + + for (int j = 4; j >= 0; j -= 4) { + int remainder = (currentByte >> j) & 0xf; + char hexChar = 0; -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file + hexChar = remainder < 10 ? '0' + remainder : 'A' + (remainder - 10); + + output += hexChar; + } + } + output = "0x" + output; + std::cout << output << std::endl; +} From 1aaa0c9991efb803ea229a5f93548386cb211f75 Mon Sep 17 00:00:00 2001 From: Radiy Date: Mon, 8 Dec 2025 15:59:21 +0500 Subject: [PATCH 13/49] add (solution): add pretty_array task --- 02_week/tasks/pretty_array/pretty_array.cpp | 37 +++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/02_week/tasks/pretty_array/pretty_array.cpp b/02_week/tasks/pretty_array/pretty_array.cpp index 48eab341..15895d31 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,37 @@ +#include #include +#include -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +void PrintArray(const int* begin, const int* end, int constrainer = 0) { + if (begin == nullptr || end == nullptr) { + std::cout << "[]" << std::endl; + return; + } + + std::string output = "["; + + size_t size = std::abs(begin - end); + + const int* arr = begin > end ? end + 1 : begin; + size_t startIndex = begin > end ? size - 1 : 0; + int step = begin > end ? -1 : 1; + size_t charCntr = 0; + + for (size_t i = startIndex; i < size; i += step) { + if (i != startIndex) { + output.append(", "); + if ((constrainer > 0) && (charCntr % constrainer == 0)) { + output.append("...\n "); + charCntr = 0; + } + } + + output.append(std::to_string(arr[i])); + charCntr++; + } + + output += "]"; + + std::cout << output << std::endl; +} From 12fe9b938308e705303fe83082393b0b3b9715d5 Mon Sep 17 00:00:00 2001 From: Radiy Date: Sun, 14 Dec 2025 23:04:03 +0500 Subject: [PATCH 14/49] add (solution): add data_stats task --- 03_week/tasks/data_stats/data_stats.cpp | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index b941c211..3a29de14 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -1,11 +1,27 @@ -#include - +#include +#include struct DataStats { double avg = 0.0; double sd = 0.0; }; -/* return_type */ CalculateDataStats(/* args */) { - throw std::runtime_error{"Not implemented"}; +struct DataStats CalculateDataStats(const std::vector &v) { + if (v.empty()) { + return {0.0, 0.0}; + } + + long sum = 0; + long sumSq = 0; + + for (auto val : v) { + sum += val; + sumSq += static_cast(val) * val; + } + + auto n = v.size(); + double avg = static_cast(sum) / n; + double variance = (sumSq - (static_cast(sum) * sum) / n) / n; + + return { avg, std::sqrt(variance) }; } From 45ed16c796052db0d8874dcc7e21bd144da196f1 Mon Sep 17 00:00:00 2001 From: Radiy Date: Mon, 15 Dec 2025 16:55:09 +0500 Subject: [PATCH 15/49] add (solution): add easy_compare task --- 03_week/tasks/easy_compare/easy_compare.cpp | 51 ++++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/03_week/tasks/easy_compare/easy_compare.cpp b/03_week/tasks/easy_compare/easy_compare.cpp index dd5cb7f6..a84d6e43 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -1,10 +1,38 @@ #include - +#include struct Date { unsigned year; unsigned month; unsigned day; + + bool operator==(const Date& other) const { + return std::tie(year, month, day) == std::tie(other.year, other.month, other.day); + } + + bool operator!=(const Date& other) const { + return !(*this == other); + } + + bool operator<(const Date& other) const { + return std::tie(year, month, day) < std::tie(other.year, other.month, other.day); + } + + bool operator>(const Date& other) const { + if (*this == other) { + return false; + } + + return !(*this < other); + } + + bool operator<=(const Date& other) { + return !(*this > other); + } + + bool operator>=(const Date& other) { + return !(*this < other); + } }; struct StudentInfo { @@ -13,4 +41,23 @@ struct StudentInfo { int score; unsigned course; Date birth_date; -}; \ No newline at end of file + + bool operator==(const StudentInfo& other) const { + return mark == other.mark && score == other.score; + } + + bool operator!=(const StudentInfo& other) const { + return !(*this == other); + } + + bool operator<(const StudentInfo& other) const { + // обратный знак, так как A < Z в таблице символов + return std::tie(other.mark, score, other.course, birth_date) < std::tie(mark, other.score, course, other.birth_date); + // if (mark != other.mark) return mark > other.mark; + // if (score != other.score) return score < other.score; + // if (course != other.course) return course > other.course; + // return birth_date < other.birth_date; + } +}; + + From 44d87621215980b44e13f197e381595e014c8c14 Mon Sep 17 00:00:00 2001 From: Radiy Date: Mon, 15 Dec 2025 17:11:51 +0500 Subject: [PATCH 16/49] add (solution): add find_all task --- 03_week/tasks/find_all/find_all.cpp | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/03_week/tasks/find_all/find_all.cpp b/03_week/tasks/find_all/find_all.cpp index 74f393b2..252f2b15 100644 --- a/03_week/tasks/find_all/find_all.cpp +++ b/03_week/tasks/find_all/find_all.cpp @@ -1,6 +1,22 @@ #include +typedef bool (*Predicate)(int); -/* return_type */ FindAll(/* args */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +std::vector FindAll(const std::vector &v, Predicate predicate_func) { + if (v.empty() || predicate_func == nullptr) { + return {}; + } + + std::vector output; + output.reserve(v.size()); + + for (size_t i = 0; i < v.size(); ++i) { + if (predicate_func(v[i])) { + output.push_back(i); + } + } + + output.shrink_to_fit(); + + return output; +} From 8504d0e3b1f5ee1343e641783682a5a2effbe7d2 Mon Sep 17 00:00:00 2001 From: Radiy Date: Mon, 15 Dec 2025 17:31:29 +0500 Subject: [PATCH 17/49] WIP task filter --- 03_week/tasks/filter/filter.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index 6648cb39..d9ccd91e 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -1,6 +1,17 @@ #include +typedef bool (*Predicate)(int); -/* return_type */ Filter(/* args */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +void Filter(std::vector &v, Predicate predicateFunc) { + if (v.empty() || predicateFunc == nullptr) { + return; + } + + for (auto it = v.begin(); it != v.end();) { + if (predicateFunc(*it)) { + it = v.erase(it); + } else { + ++it; + } + } +} From 6b566ab49004acba0da9066e26aa2feaaaf22a29 Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 17 Dec 2025 18:22:22 +0500 Subject: [PATCH 18/49] WIP enum operators --- .../tasks/enum_operators/enum_operators.cpp | 56 +++++++++++++++---- 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/03_week/tasks/enum_operators/enum_operators.cpp b/03_week/tasks/enum_operators/enum_operators.cpp index a539be38..5a23d1ae 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 +#include +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -12,22 +14,52 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -/* return_type */ operator|(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Для GoogleTest +explicit operator bool(CheckFlags f) { + return static_cast>(f) != 0; } -/* return_type */ operator&(/* args */) { - throw std::runtime_error{"Not implemented"}; +bool operator!(const CheckFlags f) { + return static_cast>(f) == 0; } -/* return_type */ operator^(/* args */) { - throw std::runtime_error{"Not implemented"}; +bool operator==(CheckFlags lhs, CheckFlags rhs) { + return static_cast>(lhs) == + static_cast>(rhs); } -/* return_type */ operator~(/* args */) { - throw std::runtime_error{"Not implemented"}; +bool operator!=(CheckFlags lhs, CheckFlags rhs) { + return !(lhs == rhs); } -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator|(CheckFlags lhs, CheckFlags rhs) { + return static_cast( + (static_cast>(lhs) | + static_cast>(rhs)) & static_cast>(CheckFlags::ALL) + ); +} + +CheckFlags operator&(CheckFlags lhs, CheckFlags rhs) { + auto uintLhs = static_cast>(lhs); + auto uintRhs = static_cast>(rhs); + + return static_cast(uintLhs & uintRhs); +} + +CheckFlags operator^(CheckFlags lhs, CheckFlags rhs) { + return static_cast( + static_cast>(lhs) ^ + static_cast>(rhs) + ); +} + +CheckFlags operator~(const CheckFlags& f) { + return static_cast(~static_cast>(f)); +} + +std::ostream& operator<<(std::ostream& os, const CheckFlags& f) { + if (f == CheckFlags::ALL) { + return os; + } + return os; } From d455bf1f1e50dcbf567f678014613600380cabee Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 11:52:37 +0500 Subject: [PATCH 19/49] add (solution): add enum_operators task --- .../tasks/enum_operators/enum_operators.cpp | 71 +++++++++++++------ 1 file changed, 50 insertions(+), 21 deletions(-) diff --git a/03_week/tasks/enum_operators/enum_operators.cpp b/03_week/tasks/enum_operators/enum_operators.cpp index 5a23d1ae..61599cfc 100644 --- a/03_week/tasks/enum_operators/enum_operators.cpp +++ b/03_week/tasks/enum_operators/enum_operators.cpp @@ -1,7 +1,11 @@ +#include #include +#include #include +#include #include #include +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -14,18 +18,26 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -// Для GoogleTest -explicit operator bool(CheckFlags f) { - return static_cast>(f) != 0; +const std::vector> checkNames = { + {CheckFlags::TIME, "TIME"}, + {CheckFlags::DATE, "DATE"}, + {CheckFlags::USER, "USER"}, + {CheckFlags::CERT, "CERT"}, + {CheckFlags::KEYS, "KEYS"}, + {CheckFlags::DEST, "DEST"}, +}; + +std::underlying_type_t getVal(CheckFlags f) { + return static_cast>(f) & + static_cast>(CheckFlags::ALL); } bool operator!(const CheckFlags f) { - return static_cast>(f) == 0; + return getVal(f) == 0; } bool operator==(CheckFlags lhs, CheckFlags rhs) { - return static_cast>(lhs) == - static_cast>(rhs); + return getVal(lhs) == getVal(rhs); } bool operator!=(CheckFlags lhs, CheckFlags rhs) { @@ -33,33 +45,50 @@ bool operator!=(CheckFlags lhs, CheckFlags rhs) { } CheckFlags operator|(CheckFlags lhs, CheckFlags rhs) { - return static_cast( - (static_cast>(lhs) | - static_cast>(rhs)) & static_cast>(CheckFlags::ALL) - ); + return static_cast((getVal(lhs) | getVal(rhs)) & getVal(CheckFlags::ALL)); } -CheckFlags operator&(CheckFlags lhs, CheckFlags rhs) { - auto uintLhs = static_cast>(lhs); - auto uintRhs = static_cast>(rhs); +bool operator&(CheckFlags lhs, CheckFlags rhs) { + auto lhsVal = getVal(lhs); + auto rhsVal = getVal(rhs); + + if (lhsVal == 0 || rhsVal == 0) { + return false; + } - return static_cast(uintLhs & uintRhs); + return ((lhsVal & rhsVal) == lhsVal) || ((lhsVal & rhsVal) == rhsVal); } CheckFlags operator^(CheckFlags lhs, CheckFlags rhs) { - return static_cast( - static_cast>(lhs) ^ - static_cast>(rhs) - ); + return static_cast((getVal(lhs) ^ getVal(rhs)) & getVal(CheckFlags::ALL)); } CheckFlags operator~(const CheckFlags& f) { - return static_cast(~static_cast>(f)); + return static_cast((~getVal(f)) & getVal(CheckFlags::ALL)); } std::ostream& operator<<(std::ostream& os, const CheckFlags& f) { - if (f == CheckFlags::ALL) { + std::string needed_checks = ""; + + auto fVal = getVal(f); + + if (f == CheckFlags::NONE) { + os << "NONE"; return os; - } + } + + bool first = true; + for (const auto& [key, val] : checkNames) { + if (fVal & getVal(key)) { + if (!first) { + needed_checks += ", "; + } + + needed_checks += val; + first = false; + } + } + + os << needed_checks; return os; } From 7a87f24679e351e5beb75d302c8fa1db87bc74d1 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 12:22:23 +0500 Subject: [PATCH 20/49] add (solution): add unique task --- 03_week/tasks/unique/unique.cpp | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/03_week/tasks/unique/unique.cpp b/03_week/tasks/unique/unique.cpp index 9d2545bb..bec3950b 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -1,6 +1,18 @@ -#include #include -/* return_type */ Unique(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::vector Unique(const std::vector& v) { + std::vector uniqueElem{}; + + uniqueElem.reserve(v.size()); + + + for (auto val : v) { + if (uniqueElem.empty() || (uniqueElem.back() != val)) { + uniqueElem.push_back(val); + } + } + + uniqueElem.shrink_to_fit(); + + return uniqueElem; } From 5afec6c6656b25ccafd210a95afb5a3adaff4266 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 13:15:27 +0500 Subject: [PATCH 21/49] add (solution): add range task --- 03_week/tasks/range/range.cpp | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index d2085495..fe27b102 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -1,7 +1,33 @@ -#include +#include +#include +#include #include -std::vector Range(int from, int to, int step) { - throw std::runtime_error{"Not implemented"}; +std::vector Range(int from, int to, int step = 1) { + std::vector range{}; + + if (step == 0) { + return range; + } + + if (step < 0 && from < to) { + return range; + } + + if (step > 0 && from > to) { + return range; + } + + auto absDiff = std::abs(from - to); + + range.reserve(std::ceil(std::abs(absDiff / static_cast(step)))); + + int val = from; + for (size_t i = 0; i < range.capacity(); ++i) { + range.push_back(val); + val += step; + } + + return range; } From 0c21b295324c2423d3ae8d2a62d36360c23052b5 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 14:20:02 +0500 Subject: [PATCH 22/49] add (solution): add os_overoad task --- 03_week/tasks/os_overload/os_overload.cpp | 64 ++++++++++++++++++++--- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/03_week/tasks/os_overload/os_overload.cpp b/03_week/tasks/os_overload/os_overload.cpp index e473418d..b62c77e6 100644 --- a/03_week/tasks/os_overload/os_overload.cpp +++ b/03_week/tasks/os_overload/os_overload.cpp @@ -1,21 +1,73 @@ -#include +#include #include #include struct Coord2D { - int x; - int y; + int x = 0; + int y = 0; }; struct Circle { Coord2D coord; - unsigned radius; + unsigned radius = 1; }; 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& c) { + + if (c.radius == 0) { + os << "circle[]"; + return os; + } + + os << "circle[" << c.coord << ", " << "r = " << c.radius << ']'; + + return os; +} + +std::ostream& operator<<(std::ostream& os, const CircleRegion& r) { + if (r.second == true) { + os << '+'; + } else { + os << '-'; + } + + os << r.first; + + return os; +} + +std::ostream& operator<<(std::ostream& os, const CircleRegionList& lst) { + if (lst.empty()) { + os << "{}"; + return os; + } + + os << "{"; + + bool first = true; + + for (auto val : lst) { + if (!first) { + os << ','; + } + + os << std::endl << '\t' << val; + + first = false; + } + + os << std::endl <<"}"; + + return os; } From 7bc19a16c773ff5920d481f00d31a6e145f7d864 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 14:48:57 +0500 Subject: [PATCH 23/49] add (solution): add minmax task --- 03_week/tasks/minmax/minmax.cpp | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/03_week/tasks/minmax/minmax.cpp b/03_week/tasks/minmax/minmax.cpp index c2869799..c7ddcbce 100644 --- a/03_week/tasks/minmax/minmax.cpp +++ b/03_week/tasks/minmax/minmax.cpp @@ -1,6 +1,28 @@ -#include +#include +#include +#include +std::pair::const_iterator, std::vector::const_iterator> MinMax(const std::vector& v) { + if (v.empty()) { + return {v.end(), v.end()}; + } -/* return_type */ MinMax(/* args */) { - throw std::runtime_error{"Not implemented"}; + auto minIt = v.begin(); + auto maxIt = v.end(); + int min = INT_MAX; + int max = INT_MIN; + + for (auto it = v.begin(); it != v.end(); ++it) { + if (*it < min) { + min = *it; + minIt = it; + } + + if (*it >= max) { + max = *it; + maxIt = it; + } + } + + return {minIt, maxIt}; } From f128b9ca2aefc7b8aa6cfc8c88eea076485ab7b1 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 14:50:45 +0500 Subject: [PATCH 24/49] removed 04_week tests --- 04_week/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/04_week/CMakeLists.txt b/04_week/CMakeLists.txt index 0531237e..97b68f15 100644 --- a/04_week/CMakeLists.txt +++ b/04_week/CMakeLists.txt @@ -7,9 +7,9 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использов set(EXAMPLES_DIR examples) # Определим переменную с именем директории set(TASKS_DIR tasks) -add_subdirectory(tasks) +# add_subdirectory(tasks) # Создать исполняемый файл для каждого примера if (BUILD_EXAMPLES_04_WEEK) # add_example(struct_examples ${EXAMPLES_DIR}/struct_examples.cpp) -endif() \ No newline at end of file +endif() From 42b81c6930f30131410b372ee0271a4c5befc9b3 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 15:08:18 +0500 Subject: [PATCH 25/49] add (solution): add filter task --- 03_week/tasks/filter/filter.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index d9ccd91e..979f1c1e 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -1,4 +1,4 @@ -#include +#include typedef bool (*Predicate)(int); @@ -8,7 +8,7 @@ void Filter(std::vector &v, Predicate predicateFunc) { } for (auto it = v.begin(); it != v.end();) { - if (predicateFunc(*it)) { + if (!predicateFunc(*it)) { it = v.erase(it); } else { ++it; From 23e327eac06bdf07a0002b4f917ffadbd093efcb Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 15:12:03 +0500 Subject: [PATCH 26/49] add (fix): add easy_compare task --- 03_week/tasks/easy_compare/easy_compare.cpp | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/03_week/tasks/easy_compare/easy_compare.cpp b/03_week/tasks/easy_compare/easy_compare.cpp index a84d6e43..7436856d 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -2,9 +2,9 @@ #include struct Date { - unsigned year; - unsigned month; - unsigned day; + unsigned year = 0; + unsigned month = 0; + unsigned day = 0; bool operator==(const Date& other) const { return std::tie(year, month, day) == std::tie(other.year, other.month, other.day); @@ -53,10 +53,6 @@ struct StudentInfo { bool operator<(const StudentInfo& other) const { // обратный знак, так как A < Z в таблице символов return std::tie(other.mark, score, other.course, birth_date) < std::tie(mark, other.score, course, other.birth_date); - // if (mark != other.mark) return mark > other.mark; - // if (score != other.score) return score < other.score; - // if (course != other.course) return course > other.course; - // return birth_date < other.birth_date; } }; From e81fc9cc1d2f595978393a244f1a52248031761c Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 18 Dec 2025 15:25:08 +0500 Subject: [PATCH 27/49] add (optimisation): add filter task --- 03_week/tasks/filter/filter.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index 979f1c1e..64cc2779 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -6,12 +6,18 @@ void Filter(std::vector &v, Predicate predicateFunc) { if (v.empty() || predicateFunc == nullptr) { return; } - - for (auto it = v.begin(); it != v.end();) { - if (!predicateFunc(*it)) { - it = v.erase(it); - } else { - ++it; + + auto secondIt = v.begin(); + size_t newSize = 0; + for (auto it = v.begin(); it != v.end(); ++it) { + if (predicateFunc(*it)) { + if (it != secondIt) { + *secondIt = *it; + } + ++secondIt; + ++newSize; } } + + v.resize(newSize); } From 83f3bcebd2f90382a58aaad5336b616e587da47b Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 19 Dec 2025 17:34:40 +0500 Subject: [PATCH 28/49] Removed CMakeLists backups --- 04_week/CMakeLists_BACKUP_1018.txt | 20 -------------------- 04_week/CMakeLists_BACKUP_946.txt | 20 -------------------- 04_week/CMakeLists_BASE_1018.txt | 15 --------------- 04_week/CMakeLists_BASE_946.txt | 15 --------------- 04_week/CMakeLists_LOCAL_1018.txt | 15 --------------- 04_week/CMakeLists_LOCAL_946.txt | 15 --------------- 04_week/CMakeLists_REMOTE_1018.txt | 15 --------------- 04_week/CMakeLists_REMOTE_946.txt | 15 --------------- 8 files changed, 130 deletions(-) delete mode 100644 04_week/CMakeLists_BACKUP_1018.txt delete mode 100644 04_week/CMakeLists_BACKUP_946.txt delete mode 100644 04_week/CMakeLists_BASE_1018.txt delete mode 100644 04_week/CMakeLists_BASE_946.txt delete mode 100644 04_week/CMakeLists_LOCAL_1018.txt delete mode 100644 04_week/CMakeLists_LOCAL_946.txt delete mode 100644 04_week/CMakeLists_REMOTE_1018.txt delete mode 100644 04_week/CMakeLists_REMOTE_946.txt diff --git a/04_week/CMakeLists_BACKUP_1018.txt b/04_week/CMakeLists_BACKUP_1018.txt deleted file mode 100644 index f49b3f42..00000000 --- a/04_week/CMakeLists_BACKUP_1018.txt +++ /dev/null @@ -1,20 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -# add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -<<<<<<< HEAD -# add_example(struct_examples ${EXAMPLES_DIR}/struct_examples.cpp) -endif() -======= -# add_example(class_examples ${EXAMPLES_DIR}/class_examples.cpp) -endif() ->>>>>>> 03c8f52452515f446a786675ecaff9cf59a0f216 diff --git a/04_week/CMakeLists_BACKUP_946.txt b/04_week/CMakeLists_BACKUP_946.txt deleted file mode 100644 index f49b3f42..00000000 --- a/04_week/CMakeLists_BACKUP_946.txt +++ /dev/null @@ -1,20 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -# add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -<<<<<<< HEAD -# add_example(struct_examples ${EXAMPLES_DIR}/struct_examples.cpp) -endif() -======= -# add_example(class_examples ${EXAMPLES_DIR}/class_examples.cpp) -endif() ->>>>>>> 03c8f52452515f446a786675ecaff9cf59a0f216 diff --git a/04_week/CMakeLists_BASE_1018.txt b/04_week/CMakeLists_BASE_1018.txt deleted file mode 100644 index 0531237e..00000000 --- a/04_week/CMakeLists_BASE_1018.txt +++ /dev/null @@ -1,15 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -# add_example(struct_examples ${EXAMPLES_DIR}/struct_examples.cpp) -endif() \ No newline at end of file diff --git a/04_week/CMakeLists_BASE_946.txt b/04_week/CMakeLists_BASE_946.txt deleted file mode 100644 index 0531237e..00000000 --- a/04_week/CMakeLists_BASE_946.txt +++ /dev/null @@ -1,15 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -# add_example(struct_examples ${EXAMPLES_DIR}/struct_examples.cpp) -endif() \ No newline at end of file diff --git a/04_week/CMakeLists_LOCAL_1018.txt b/04_week/CMakeLists_LOCAL_1018.txt deleted file mode 100644 index 97b68f15..00000000 --- a/04_week/CMakeLists_LOCAL_1018.txt +++ /dev/null @@ -1,15 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -# add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -# add_example(struct_examples ${EXAMPLES_DIR}/struct_examples.cpp) -endif() diff --git a/04_week/CMakeLists_LOCAL_946.txt b/04_week/CMakeLists_LOCAL_946.txt deleted file mode 100644 index 97b68f15..00000000 --- a/04_week/CMakeLists_LOCAL_946.txt +++ /dev/null @@ -1,15 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -# add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -# add_example(struct_examples ${EXAMPLES_DIR}/struct_examples.cpp) -endif() diff --git a/04_week/CMakeLists_REMOTE_1018.txt b/04_week/CMakeLists_REMOTE_1018.txt deleted file mode 100644 index b15ca37c..00000000 --- a/04_week/CMakeLists_REMOTE_1018.txt +++ /dev/null @@ -1,15 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -# add_example(class_examples ${EXAMPLES_DIR}/class_examples.cpp) -endif() \ No newline at end of file diff --git a/04_week/CMakeLists_REMOTE_946.txt b/04_week/CMakeLists_REMOTE_946.txt deleted file mode 100644 index b15ca37c..00000000 --- a/04_week/CMakeLists_REMOTE_946.txt +++ /dev/null @@ -1,15 +0,0 @@ -cmake_minimum_required(VERSION 3.14) # Минимальная требуемая версия CMake -project(04_week) # Необходим для инициализации cmake - -set(CMAKE_CXX_STANDARD 20) # Версия стандарта C++ -set(CMAKE_CXX_STANDARD_REQUIRED ON) # Гарантирует использование указанной версии стандарта - -set(EXAMPLES_DIR examples) # Определим переменную с именем директории -set(TASKS_DIR tasks) - -add_subdirectory(tasks) - -# Создать исполняемый файл для каждого примера -if (BUILD_EXAMPLES_04_WEEK) -# add_example(class_examples ${EXAMPLES_DIR}/class_examples.cpp) -endif() \ No newline at end of file From 55ccf150a1228d8ca1e12db218685c5e16fd83c9 Mon Sep 17 00:00:00 2001 From: Radiy Date: Sun, 21 Dec 2025 14:19:46 +0500 Subject: [PATCH 29/49] add (solution): add stack task --- 04_week/tasks/stack/stack.cpp | 58 ++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/04_week/tasks/stack/stack.cpp b/04_week/tasks/stack/stack.cpp index 222e4ffc..5f9241ed 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -1,6 +1,62 @@ +#include #include - class Stack { +public: + void Push(int val); + 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 { + return this->stack_ == other.stack_; + } + bool operator!=(const Stack& other) const { + return !(*this == other); + } + +private: + std::vector stack_{}; }; + +void Stack::Push(int val) { + stack_.push_back(val); +} + +bool Stack::Pop() { + if (stack_.empty()) { + return false; + } + + stack_.pop_back(); + return true; +} + +int& Stack::Top() { + return stack_.back(); +} + +const int& Stack::Top() const { + return stack_.back(); +} + +bool Stack::Empty() const { + return stack_.empty(); +} + +size_t Stack::Size() const { + return stack_.size(); +} + +void Stack::Clear() { + stack_.clear(); +} + +void Stack::Swap(Stack& other) { + stack_.swap(other.stack_); +} From 5b5b649425615f01c47218858caeab283b498d2f Mon Sep 17 00:00:00 2001 From: Radiy Date: Tue, 23 Dec 2025 18:33:48 +0500 Subject: [PATCH 30/49] add (solution): add queue task --- 04_week/tasks/queue/queue.cpp | 127 +++++++++++++++++++++++++++++++++- CMakeLists.txt | 2 +- 2 files changed, 127 insertions(+), 2 deletions(-) diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 2a9f8493..526f3706 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,6 +1,131 @@ +#include +#include +#include #include - class Queue { +public: + Queue() {}; + + Queue(std::stack s) { + outputV_.reserve(s.size()); + while(!s.empty()) { + outputV_.push_back(s.top()); + s.pop(); + } + }; + + Queue(std::vector v) : outputV_(v.rbegin(), v.rend()){}; + + Queue(std::initializer_list list) : inputV_(list) {}; + + Queue(size_t size) { + inputV_.reserve(size); + outputV_.reserve(size); + } + + void Push(int val); + 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 { + if (Size() != other.Size()) { + return false; + } + + return this->GetQueueAsVector() == other.GetQueueAsVector(); + } + bool operator!=(const Queue& other) const { + return !(*this == other); + } + +private: + void CopyIfOutEmpty(); + std::vector GetQueueAsVector() const; + std::vector inputV_{}; + std::vector outputV_{}; }; + +void Queue::CopyIfOutEmpty() { + if (outputV_.empty()) { + outputV_ = std::vector(inputV_.rbegin(), inputV_.rend()); + inputV_.clear(); + } +} + +std::vector Queue::GetQueueAsVector() const { + std::vector tOut = outputV_; + tOut.insert(tOut.end(), inputV_.rbegin(), inputV_.rend()); + return tOut; +} + +void Queue::Push(int val) { + inputV_.push_back(val); +} + +bool Queue::Pop() { + if (outputV_.empty() && inputV_.empty()) { + return false; + } + + CopyIfOutEmpty(); + + outputV_.pop_back(); + + return true; +} + +int& Queue::Front() { + CopyIfOutEmpty(); + return outputV_.back(); +} + +const int& Queue::Front() const { + if (outputV_.empty()) { + return inputV_.front(); + } + + return outputV_.back(); +} + +int& Queue::Back() { + if (!inputV_.empty()) { + return inputV_.back(); + } + + return outputV_.front(); +} + +const int& Queue::Back() const { + if (!inputV_.empty()) { + return inputV_.back(); + } + + return outputV_.front(); +} + +bool Queue::Empty() const { + return (inputV_.empty() && outputV_.empty()); +} + +size_t Queue::Size() const { + return (inputV_.size() + outputV_.size()); +} + +void Queue::Clear() { + inputV_.clear(); + outputV_.clear(); +} + +void Queue::Swap(Queue& other) { + inputV_.swap(other.inputV_); + outputV_.swap(other.outputV_); +} diff --git a/CMakeLists.txt b/CMakeLists.txt index b64ab3cd..fc3d5fa2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,4 +33,4 @@ add_week(06_week) add_week(07_week) add_week(08_week) add_week(09_week) -add_week(10_week) \ No newline at end of file +add_week(10_week) From bd18c29a67537969d8d467528023ab8cc83f2ebd Mon Sep 17 00:00:00 2001 From: Radiy Date: Tue, 23 Dec 2025 18:55:48 +0500 Subject: [PATCH 31/49] fix (solution): add queue fix --- 04_week/tasks/queue/queue.cpp | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 526f3706..77bdac17 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -19,12 +18,17 @@ class Queue { Queue(std::initializer_list list) : inputV_(list) {}; - Queue(size_t size) { + Queue(const size_t size) { inputV_.reserve(size); outputV_.reserve(size); - } + }; + + Queue(const int size) { + inputV_.reserve(size); + outputV_.reserve(size); + }; - void Push(int val); + inline void Push(int val); bool Pop(); int& Front(); const int& Front() const; @@ -62,12 +66,16 @@ void Queue::CopyIfOutEmpty() { } std::vector Queue::GetQueueAsVector() const { - std::vector tOut = outputV_; - tOut.insert(tOut.end(), inputV_.rbegin(), inputV_.rend()); - return tOut; + std::vector result; + + std::copy(outputV_.rbegin(), outputV_.rend(), std::back_inserter(result)); + + std::copy(inputV_.begin(), inputV_.end(), std::back_inserter(result)); + + return result; } -void Queue::Push(int val) { +inline void Queue::Push(int val) { inputV_.push_back(val); } From 0ebcff7ad448609c772c341908ced122cd9553f1 Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 24 Dec 2025 17:46:28 +0500 Subject: [PATCH 32/49] wip ring buffer --- 04_week/tasks/ring_buffer/ring_buffer.cpp | 52 ++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index e2b57ba2..520d3758 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -1,6 +1,56 @@ +#include #include - class RingBuffer { +public: + RingBuffer() { + ringBuff.reserve(1); + frontIt = ringBuff.begin(); + backIt = ringBuff.begin(); + } + + RingBuffer(size_t size) { + ringBuff.reserve(size); + frontIt = ringBuff.begin(); + backIt = ringBuff.begin(); + }; + + RingBuffer(size_t size, int iVal) : ringBuff(size, iVal), \ + frontIt(ringBuff.end() - 1), backIt(ringBuff.begin() - 1) {}; + + RingBuffer(std::initializer_list list) : ringBuff(list), frontIt(ringBuff.end() - 1), backIt(ringBuff.begin()) {}; + void Push(int val); + bool TryPush(int val); + void Pop(); + bool TryPop(); + 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(); + std::vector Vector() const; + + int oldestElement = 0; + + +private: + std::vector ringBuff{}; + std::vector::iterator frontIt; + std::vector::iterator backIt; }; + +void RingBuffer::Push(int val) { + if ((frontIt + 1) != backIt) { + *frontIt = val; + ++frontIt; + } + + +} + From 0a479ebde7e991f4a1b5914ea80c8825e9bccfac Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 24 Dec 2025 18:09:01 +0500 Subject: [PATCH 33/49] wip ring_buff 2 --- 04_week/tasks/ring_buffer/ring_buffer.cpp | 62 +++++++++++++++++++++-- 1 file changed, 58 insertions(+), 4 deletions(-) diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index 520d3758..814450bf 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -23,7 +23,7 @@ class RingBuffer { void Push(int val); bool TryPush(int val); void Pop(); - bool TryPop(); + bool TryPop(int& val); int& Front(); const int& Front() const; int& Back(); @@ -46,11 +46,65 @@ class RingBuffer { }; void RingBuffer::Push(int val) { - if ((frontIt + 1) != backIt) { - *frontIt = val; - ++frontIt; + ++frontIt; + + if (frontIt == ringBuff.end()) { + frontIt = ringBuff.begin(); + } + + if (frontIt == backIt) { + ++backIt; + } + + if (backIt == ringBuff.end()) { + backIt = ringBuff.begin(); + } + + *frontIt = val; +} + +bool RingBuffer::TryPush(int val) { + ++frontIt; + + if (frontIt == ringBuff.end()) { + frontIt = ringBuff.begin(); + } + + if (frontIt == backIt) { + --frontIt; + return false; } + *frontIt = val; + return true; +} + +void RingBuffer::Pop() { + if (backIt == frontIt) { + return; + } + + ++backIt; + + if (backIt == ringBuff.end()) { + backIt = ringBuff.begin(); + } +} + +bool RingBuffer::TryPop(int& val) { + if (backIt == frontIt) { + return false; + } + + val = *backIt; + + ++backIt; + + if (backIt == ringBuff.end()) { + backIt = ringBuff.begin(); + } + + return true; } From 270198a315edb818c02a71a7857d9383333366a1 Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 24 Dec 2025 18:20:18 +0500 Subject: [PATCH 34/49] wip ring_buffer 3 --- 04_week/tasks/ring_buffer/ring_buffer.cpp | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index 814450bf..16ecfc1c 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -107,4 +107,29 @@ bool RingBuffer::TryPop(int& val) { return true; } + +int& RingBuffer::Front() { + return *frontIt; +} + +const int& RingBuffer::Front() const { + return *frontIt; +} +int& RingBuffer::Back() { + return *backIt; +} + +const int& RingBuffer::Back() const { + return *backIt; +} + +bool RingBuffer::Empty() const { + return backIt == frontIt; // will be wrong on circ buffer size of one +} + +bool RingBuffer::Full() const { + return (frontIt + 1) == backIt; // also will be wrong on buffer size of one +} + + From 8f37dc1089c8823b23a144f04f38d0f987ae76ed Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 24 Dec 2025 21:07:45 +0500 Subject: [PATCH 35/49] wip ring_buffer 4 --- 04_week/tasks/ring_buffer/ring_buffer.cpp | 214 +++++++++++++++------- 1 file changed, 150 insertions(+), 64 deletions(-) diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index 16ecfc1c..f5b2ad5e 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -1,24 +1,45 @@ +#include #include #include class RingBuffer { public: - RingBuffer() { - ringBuff.reserve(1); - frontIt = ringBuff.begin(); - backIt = ringBuff.begin(); - } + RingBuffer() : ringBuff(1), head(0), tail(0), size(0) {} - RingBuffer(size_t size) { - ringBuff.reserve(size); - frontIt = ringBuff.begin(); - backIt = ringBuff.begin(); - }; + RingBuffer(size_t capacity) : head(0), tail(0), size(0) { + if (capacity == 0) { + ++capacity; + } + ringBuff.reserve(capacity); + } - RingBuffer(size_t size, int iVal) : ringBuff(size, iVal), \ - frontIt(ringBuff.end() - 1), backIt(ringBuff.begin() - 1) {}; + RingBuffer(size_t capacity, int iVal) : head(capacity), tail(0), + isFull(true), isEmpty(false) { + + if (capacity == 0) { + ++capacity; + } + size = capacity; + ringBuff.resize(capacity); + std::fill(ringBuff.begin(), ringBuff.end(), iVal); + } - RingBuffer(std::initializer_list list) : ringBuff(list), frontIt(ringBuff.end() - 1), backIt(ringBuff.begin()) {}; + RingBuffer(std::initializer_list list) : tail(0), isFull(true), isEmpty(false) { + if (list.size() != 0) { + size = list.size(); + head = size; + ringBuff.resize(size); + std::copy(list.begin(), list.end(), ringBuff.begin()); + return; + } + + size = 0; + head = 0; + ringBuff.resize(1); + ringBuff[0] = 0; + isFull = false; + isEmpty = true; + } void Push(int val); bool TryPush(int val); @@ -33,103 +54,168 @@ class RingBuffer { size_t Size() const; size_t Capacity() const; void Clear(); - void Resize(); + void Resize(size_t newSize); std::vector Vector() const; - - int oldestElement = 0; - + int& operator[](size_t idx) { + return ringBuff[(tail + idx) % ringBuff.size()]; + } + + const int& operator[](size_t idx) const { + return ringBuff[(tail + idx) % ringBuff.size()]; + } + private: std::vector ringBuff{}; - std::vector::iterator frontIt; - std::vector::iterator backIt; + size_t head = 0; + size_t tail = 0; + size_t size = 0; + bool isFull = false; + bool isEmpty = true; }; void RingBuffer::Push(int val) { - ++frontIt; - - if (frontIt == ringBuff.end()) { - frontIt = ringBuff.begin(); - } - - if (frontIt == backIt) { - ++backIt; + size_t cap = ringBuff.capacity(); + + isEmpty = false; + ringBuff[head] = val; + // при head = buff.capacity(), head снова станет = 0 + head = (head + 1) % cap; + + if (size < cap) { + ++size; + } else { + // аналогично head + tail = (tail + 1) % ringBuff.capacity(); } - if (backIt == ringBuff.end()) { - backIt = ringBuff.begin(); + if (size == cap) { + isFull = true; } - - *frontIt = val; } bool RingBuffer::TryPush(int val) { - ++frontIt; + size_t cap = ringBuff.capacity(); - if (frontIt == ringBuff.end()) { - frontIt = ringBuff.begin(); + if (isFull) { + return false; } + + isEmpty = false; + ringBuff[head] = val; + // при head = buff.capacity(), head снова станет = 0 + head = (head + 1) % cap; - if (frontIt == backIt) { - --frontIt; - return false; + ++size; + + if (size == cap) { + isFull = true; } - *frontIt = val; - - return true; + return true; } void RingBuffer::Pop() { - if (backIt == frontIt) { - return; - } - - ++backIt; + isFull = false; - if (backIt == ringBuff.end()) { - backIt = ringBuff.begin(); + if (size > 0) { + tail = (tail + 1) % ringBuff.capacity(); + --size; + } else { + isEmpty = true; } } bool RingBuffer::TryPop(int& val) { - if (backIt == frontIt) { - return false; - } - - val = *backIt; + isFull = false; - ++backIt; - - if (backIt == ringBuff.end()) { - backIt = ringBuff.begin(); + if (size > 0) { + val = ringBuff[tail]; + tail = (tail + 1) % ringBuff.capacity(); + --size; + return true; } - - return true; + + isEmpty = true; + return false; } int& RingBuffer::Front() { - return *frontIt; + return ringBuff[head - 1]; } const int& RingBuffer::Front() const { - return *frontIt; + return ringBuff[head - 1]; } int& RingBuffer::Back() { - return *backIt; + return ringBuff[tail]; } const int& RingBuffer::Back() const { - return *backIt; + return ringBuff[tail]; } bool RingBuffer::Empty() const { - return backIt == frontIt; // will be wrong on circ buffer size of one + return isEmpty; } + bool RingBuffer::Full() const { - return (frontIt + 1) == backIt; // also will be wrong on buffer size of one + return isFull; +} + +size_t RingBuffer::Size() const { + return size; +} + +size_t RingBuffer::Capacity() const { + return ringBuff.capacity(); +} + +void RingBuffer::Clear() { + head = 0; + tail = 0; + size = 0; + isFull = false; + isEmpty = true; +} + +void RingBuffer::Resize(size_t newSize) { + if (newSize == ringBuff.capacity()) { + return; + } + + size_t sz = std::min(size, newSize); + + if (sz == 0) { + ++sz; + } + + std::vector tempV; + tempV.reserve(sz); + + for (size_t i = 0; i < sz; ++i) { + tempV.push_back(ringBuff[(tail + i) % ringBuff.size()]); + } + + ringBuff.resize(newSize); + + for (size_t i = 0; i < sz; ++i) { + ringBuff[i] = std::move(tempV[i]); + } + + tail = 0; + head = sz; + size = sz; } +std::vector RingBuffer::Vector() const { + std::vector v; + v.reserve(size); + for (size_t i = 0; i < size; ++i) { + v.push_back(ringBuff[(tail + i) % ringBuff.size()]); + } + return v; + } From d05dff0d30b37183490bdc670b6782eb073e19f3 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 25 Dec 2025 14:37:34 +0500 Subject: [PATCH 36/49] add (solution): add ring_buffer task --- 04_week/tasks/ring_buffer/ring_buffer.cpp | 174 +++++++++------------- 1 file changed, 71 insertions(+), 103 deletions(-) diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index f5b2ad5e..6e798755 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -4,41 +4,18 @@ class RingBuffer { public: - RingBuffer() : ringBuff(1), head(0), tail(0), size(0) {} + RingBuffer() : ringBuff_(1), head_(0), tail_(0), size_(0) {} - RingBuffer(size_t capacity) : head(0), tail(0), size(0) { - if (capacity == 0) { - ++capacity; - } - ringBuff.reserve(capacity); - } + RingBuffer(size_t capacity) : ringBuff_(capacity > 0 ? capacity : 1), head_(0), tail_(0), size_(0) {} - RingBuffer(size_t capacity, int iVal) : head(capacity), tail(0), - isFull(true), isEmpty(false) { - - if (capacity == 0) { - ++capacity; - } - size = capacity; - ringBuff.resize(capacity); - std::fill(ringBuff.begin(), ringBuff.end(), iVal); - } + RingBuffer(size_t capacity, const int iVal) : ringBuff_(capacity > 0 ? capacity : 1, iVal), head_(capacity), tail_(0), + size_(capacity > 0 ? capacity : 1) {} - RingBuffer(std::initializer_list list) : tail(0), isFull(true), isEmpty(false) { - if (list.size() != 0) { - size = list.size(); - head = size; - ringBuff.resize(size); - std::copy(list.begin(), list.end(), ringBuff.begin()); - return; + RingBuffer(std::initializer_list list) : ringBuff_(list), head_(0), tail_(0), size_(list.size()) { + if (list.size() == 0) { + ringBuff_.reserve(1); + size_ = 0; } - - size = 0; - head = 0; - ringBuff.resize(1); - ringBuff[0] = 0; - isFull = false; - isEmpty = true; } void Push(int val); @@ -58,163 +35,154 @@ class RingBuffer { std::vector Vector() const; int& operator[](size_t idx) { - return ringBuff[(tail + idx) % ringBuff.size()]; + return ringBuff_[(tail_ + idx) % ringBuff_.size()]; } const int& operator[](size_t idx) const { - return ringBuff[(tail + idx) % ringBuff.size()]; + return ringBuff_[(tail_ + idx) % ringBuff_.size()]; } private: - std::vector ringBuff{}; - size_t head = 0; - size_t tail = 0; - size_t size = 0; - bool isFull = false; - bool isEmpty = true; + std::vector ringBuff_{}; + size_t head_ = 0; + size_t tail_ = 0; + size_t size_ = 0; }; void RingBuffer::Push(int val) { - size_t cap = ringBuff.capacity(); + size_t cap = ringBuff_.capacity(); - isEmpty = false; - ringBuff[head] = val; + ringBuff_[head_] = val; // при head = buff.capacity(), head снова станет = 0 - head = (head + 1) % cap; + head_ = (head_ + 1) % cap; - if (size < cap) { - ++size; + if (size_ < cap) { + ++size_; } else { // аналогично head - tail = (tail + 1) % ringBuff.capacity(); - } - - if (size == cap) { - isFull = true; + tail_ = (tail_ + 1) % ringBuff_.capacity(); } } bool RingBuffer::TryPush(int val) { - size_t cap = ringBuff.capacity(); + size_t cap = ringBuff_.capacity(); - if (isFull) { + if (size_ == cap) { return false; } - - isEmpty = false; - ringBuff[head] = val; + + ringBuff_[head_] = val; // при head = buff.capacity(), head снова станет = 0 - head = (head + 1) % cap; + head_ = (head_ + 1) % cap; - ++size; - - if (size == cap) { - isFull = true; - } + ++size_; return true; } void RingBuffer::Pop() { - isFull = false; - - if (size > 0) { - tail = (tail + 1) % ringBuff.capacity(); - --size; - } else { - isEmpty = true; + if (size_ > 0) { + tail_ = (tail_ + 1) % ringBuff_.capacity(); + --size_; } } bool RingBuffer::TryPop(int& val) { - isFull = false; - - if (size > 0) { - val = ringBuff[tail]; - tail = (tail + 1) % ringBuff.capacity(); - --size; + if (size_ > 0) { + val = ringBuff_[tail_]; + tail_ = (tail_ + 1) % ringBuff_.capacity(); + --size_; return true; } - isEmpty = true; return false; } int& RingBuffer::Front() { - return ringBuff[head - 1]; + if (head_ == 0) { + return ringBuff_.back(); + } + + return ringBuff_[head_ - 1]; } const int& RingBuffer::Front() const { - return ringBuff[head - 1]; + if (head_ == 0) { + return ringBuff_.back(); + } + + return ringBuff_[head_ - 1]; } int& RingBuffer::Back() { - return ringBuff[tail]; + return ringBuff_[tail_]; } const int& RingBuffer::Back() const { - return ringBuff[tail]; + return ringBuff_[tail_]; } bool RingBuffer::Empty() const { - return isEmpty; + return size_ == 0; } bool RingBuffer::Full() const { - return isFull; + return size_ == ringBuff_.capacity(); } size_t RingBuffer::Size() const { - return size; + return size_; } size_t RingBuffer::Capacity() const { - return ringBuff.capacity(); + return ringBuff_.capacity(); } void RingBuffer::Clear() { - head = 0; - tail = 0; - size = 0; - isFull = false; - isEmpty = true; + head_ = 0; + tail_ = 0; + size_ = 0; } void RingBuffer::Resize(size_t newSize) { - if (newSize == ringBuff.capacity()) { + if (newSize == 0) { + ++newSize; + } + + if (newSize == ringBuff_.size()) { return; } - size_t sz = std::min(size, newSize); - - if (sz == 0) { - ++sz; - } + size_t sz = std::min(size_, newSize); std::vector tempV; tempV.reserve(sz); for (size_t i = 0; i < sz; ++i) { - tempV.push_back(ringBuff[(tail + i) % ringBuff.size()]); + tempV.push_back(ringBuff_[(head_ - 1 - i + ringBuff_.size()) % ringBuff_.size()]); } - ringBuff.resize(newSize); + std::reverse(tempV.begin(), tempV.end()); + ringBuff_.resize(newSize); for (size_t i = 0; i < sz; ++i) { - ringBuff[i] = std::move(tempV[i]); + ringBuff_[i] = tempV[i]; } - tail = 0; - head = sz; - size = sz; + ringBuff_.shrink_to_fit(); + + tail_ = 0; + head_ = sz; + size_ = sz; } std::vector RingBuffer::Vector() const { std::vector v; - v.reserve(size); - for (size_t i = 0; i < size; ++i) { - v.push_back(ringBuff[(tail + i) % ringBuff.size()]); + v.reserve(size_); + + for (size_t i = 0; i < size_; ++i) { + v.push_back(ringBuff_[(tail_ + i) % ringBuff_.size()]); } return v; From 1da7fd812a89cc696ae7253c239d53e07463ac3b Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 26 Dec 2025 15:02:32 +0500 Subject: [PATCH 37/49] add (solution): add phasor task --- 04_week/tasks/phasor/phasor.cpp | 250 ++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) diff --git a/04_week/tasks/phasor/phasor.cpp b/04_week/tasks/phasor/phasor.cpp index 3ec1b9ad..3d5874fd 100644 --- a/04_week/tasks/phasor/phasor.cpp +++ b/04_week/tasks/phasor/phasor.cpp @@ -1,4 +1,34 @@ +#include +#include +#include +#include +namespace { + constexpr double EPS_ = 1e-12; +} + + +double DegToRad(double deg) { + return deg * M_PI / 180.0; +} + +double RadToDeg(double rad){ + return rad * 180 / M_PI; +} + +double NormalizePhase(double phase) { + phase = std::fmod(phase, 2.0 * M_PI); + + if (phase > M_PI) { + phase -= 2.0 * M_PI; + } + + if (phase <= -M_PI) { + phase += 2.0 * M_PI; + } + + return phase; +} struct ExpTag {}; struct DegTag {}; @@ -6,5 +36,225 @@ struct AlgTag {}; class Phasor { +public: + Phasor() = default; + Phasor(double A, double rad) { + if (A < 0) { + A = -A; + rad += M_PI; + } + + rad = NormalizePhase(rad); + + real_ = A * std::cos(rad); + imag_ = A * std::sin(rad); + }; + Phasor(double A, double rad, ExpTag) : Phasor(A, rad) {}; + Phasor(double A, double deg, DegTag) : Phasor(A, DegToRad(deg)) {}; + Phasor(double real, double imag, AlgTag) : real_(real), imag_(imag) {}; + + void SetPolar(double A, double rad); + 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& other) { + real_ += other.real_; + imag_ += other.imag_; + return *this; + } + + Phasor& operator-=(const Phasor& other) { + real_ -= other.real_; + imag_ -= other.imag_; + return *this; + } + Phasor& operator*=(const Phasor& other) { + SetPolar(Magnitude() * other.Magnitude(), Phase() + other.Phase()); + return *this; + } + + Phasor& operator/=(const Phasor& other) { + SetPolar(Magnitude() / other.Magnitude(), Phase() - other.Phase()); + return *this; + } + + Phasor& operator+=(double real) { + real_ += real; + return *this; + } + + Phasor& operator-=(double real) { + real_ -= real; + return *this; + } + + Phasor& operator*=(double real) { + real_ *= real; + imag_ *= real; + return *this; + } + + Phasor& operator/=(double real) { + real_ /= real; + imag_ /= real; + return *this; + } + + Phasor operator-() const { + return Phasor(-real_, -imag_, AlgTag{}); + } + +private: + double real_ = 0.0; + double imag_ = 0.0; }; + +Phasor operator+(const Phasor& lhs, const Phasor& rhs) { + double real = lhs.Real() + rhs.Real(); + double imag = lhs.Imag() + rhs.Imag(); + return Phasor(real, imag, AlgTag{}); +} + +Phasor operator-(const Phasor& lhs, const Phasor& rhs) { + double real = lhs.Real() - rhs.Real(); + double imag = lhs.Imag() - rhs.Imag(); + return Phasor(real, imag, AlgTag{}); +} + +Phasor operator*(const Phasor& lhs, const Phasor& rhs) { + double A = lhs.Magnitude() * rhs.Magnitude(); + double rad = lhs.Phase() + rhs.Phase(); + + return Phasor(A, NormalizePhase(rad)); +} + +Phasor operator/(const Phasor& lhs, const Phasor& rhs) { + double A = lhs.Magnitude() / rhs.Magnitude(); + double rad = lhs.Phase() - rhs.Phase(); + + return Phasor(A, NormalizePhase(rad)); +} + +bool operator==(const Phasor& lhs, const Phasor& rhs) { + return (std::abs(lhs.Real() - rhs.Real()) < EPS_ && + std::abs(lhs.Imag() - rhs.Imag()) < EPS_); +} + +bool operator!=(const Phasor& lhs, const Phasor& rhs) { + return !(lhs == rhs); +} + +Phasor operator+(const Phasor& lhs, double rhs) { + return Phasor(lhs.Real() + rhs, lhs.Imag(), AlgTag{}); +} + +// Сложение коммутативно +Phasor operator+(double rhs, const Phasor& lhs) { + return Phasor(lhs.Real() + rhs, lhs.Imag(), AlgTag{}); +} + +Phasor operator-(const Phasor& lhs, double rhs) { + return Phasor(lhs.Real() - rhs, lhs.Imag(), AlgTag{}); +} + +Phasor operator-(double lhs, const Phasor& rhs) { + return (lhs + (-rhs)); +} + + +Phasor operator*(const Phasor& lhs, double rhs) { + return Phasor(lhs.Real() * rhs, lhs.Imag() * rhs, AlgTag{}); +} + +// Умножение тоже коммутативно +Phasor operator*(double rhs, const Phasor& lhs) { + return Phasor(lhs.Real() * rhs, lhs.Imag() * rhs, AlgTag{}); +} + +Phasor operator/(const Phasor& lhs, double rhs) { + return Phasor(lhs.Real() / rhs, lhs.Imag() / rhs, AlgTag{}); +} + +Phasor operator/(double lhs, const Phasor& rhs) { + double A = std::abs(lhs) / rhs.Magnitude(); + double rad = ((lhs >= 0) ? 0.0 : M_PI) - rhs.Phase(); + return Phasor(A, NormalizePhase(rad)); +} + +std::ostream& operator<<(std::ostream& os, const Phasor& p) { + os << std::fixed << std::setprecision(3) + << p.Magnitude() << "*e(j*" << p.PhaseDeg() << ") [" + << p.Real() << " + j*" << p.Imag() << ']'; + return os; +} + +void Phasor::SetPolar(double A, double rad) { + *this = Phasor(A, rad); +} + +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 RadToDeg(Phase()); +} + +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 { + return 1.0 / (*this); +} + +Phasor MakePhasorCartesian(double real, double imag) { + return Phasor(real, imag, AlgTag{}); +} + +Phasor MakePhasorPolar(double A, double rad) { + return Phasor(A, rad); +} + +Phasor MakePhasorPolarDeg(double A, double deg) { + return Phasor(A, deg, DegTag{}); +} From 0a672bb9324725606357285bfdfef4e049195cf9 Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 30 Jan 2026 14:34:33 +0500 Subject: [PATCH 38/49] =?UTF-8?q?review=20fixes=20=E2=84=961?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 01_week/tasks/addition/addition.cpp | 4 +- 01_week/tasks/char_changer/char_changer.cpp | 22 +++-------- 01_week/tasks/check_flags/check_flags.cpp | 37 +++++++++--------- 01_week/tasks/quadratic/quadratic.cpp | 38 +++++++++---------- 01_week/tasks/rms/rms.cpp | 3 +- 02_week/tasks/func_array/func_array.cpp | 7 ++-- 02_week/tasks/last_of_us/last_of_us.cpp | 13 +------ 02_week/tasks/longest/longest.cpp | 12 ++---- 02_week/tasks/pretty_array/pretty_array.cpp | 5 +-- 02_week/tasks/swap_ptr/swap_ptr.cpp | 1 - 03_week/tasks/data_stats/data_stats.cpp | 8 ++-- .../tasks/enum_operators/enum_operators.cpp | 5 --- 03_week/tasks/minmax/minmax.cpp | 10 +++-- 03_week/tasks/os_overload/os_overload.cpp | 17 ++------- 03_week/tasks/range/range.cpp | 14 ++----- 03_week/tasks/unique/unique.cpp | 2 - 04_week/tasks/queue/queue.cpp | 23 +++++------ 04_week/tasks/stack/stack.cpp | 2 +- 18 files changed, 79 insertions(+), 144 deletions(-) diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index cf0b78cf..e978c805 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -1,7 +1,5 @@ #include -#include - int64_t Addition(int a, int b) { - return static_cast(a) + static_cast(b); + return static_cast(a) + b; } diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index bb92525d..f16cfde6 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -1,5 +1,5 @@ +#include #include -#include // Есть ощущение, что это можно решить как-то более лаконично и просто @@ -11,15 +11,8 @@ */ size_t GetIdenticalCharSequenceLen(char *array) { size_t sequenceLen = 0; - - if (array[0] == '\0') { - return 0; - } - - while (array[0] == array[sequenceLen]) { - ++sequenceLen; - } - + if (array[0] == '\0') return 0; + while (array[0] == array[sequenceLen]) ++sequenceLen; return sequenceLen; } @@ -28,7 +21,7 @@ size_t GetIdenticalCharSequenceLen(char *array) { * @param array указатель на начало обрабатываемого массива. * @param convertedSymIdx ссылка на индекс последнего сконвертированного символа. * @param currentSymIdx ссылка на индекс текущего обрабатываемого символа. - * @param swapChar знак, на который будет произведена замена array[convertedSymIdx]. + * @param swapChar символ, на который будет произведена замена array[convertedSymIdx]. * @return none */ void ConvertIdenticalCharacters(char array[], size_t& convertedSymIdx, size_t& currentSymIdx, char swapChar) { @@ -41,11 +34,7 @@ void ConvertIdenticalCharacters(char array[], size_t& convertedSymIdx, size_t& c return; } - if (sequenceLen >= 10) { - array[convertedSymIdx++] = '0'; - } else { - array[convertedSymIdx++] = sequenceLen + '0'; - } + array[convertedSymIdx++] = sequenceLen >= 10 ? '0' : sequenceLen + '0'; currentSymIdx += sequenceLen; } @@ -60,7 +49,6 @@ size_t CharChanger(char array[], size_t size, char delimiter = ' ') { if (isspace(array[currentSymbolIdx])) { currentSymbolIdx += GetIdenticalCharSequenceLen(&array[currentSymbolIdx]); - array[convertedSymbolIdx++] = delimiter; continue; } diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index a9a5f1f0..be3b33e7 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -1,6 +1,7 @@ #include -#include +#include #include +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -13,39 +14,35 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -// В данном случае можно было использовать map, но с ним придется использовать -// static_cast. Так же map отсортирует значения по возрасанию, соответственно -// использовать enum написанный иначе будет невозможно. -const std::vector> checkNames = { - {CheckFlags::TIME, "TIME"}, - {CheckFlags::DATE, "DATE"}, - {CheckFlags::USER, "USER"}, - {CheckFlags::CERT, "CERT"}, - {CheckFlags::KEYS, "KEYS"}, - {CheckFlags::DEST, "DEST"}, -}; +namespace { + const std::vector> checkNames = { + {CheckFlags::TIME, "TIME"}, + {CheckFlags::DATE, "DATE"}, + {CheckFlags::USER, "USER"}, + {CheckFlags::CERT, "CERT"}, + {CheckFlags::KEYS, "KEYS"}, + {CheckFlags::DEST, "DEST"}, + }; +} + void PrintCheckFlags(CheckFlags flags) { if (flags > CheckFlags::ALL) { return; } - std::string needed_checks = "["; - if (flags == CheckFlags::NONE) { - needed_checks += "]"; // Такая модификация происходит inplace, не - // создавая дорогостоящие копии - std::cout << needed_checks; + std::cout << "[]"; return; } + + std::string needed_checks = "["; bool first = true; for (const auto& [key, val] : checkNames) { if (static_cast(flags) & static_cast(key)) { if (!first) { - needed_checks += ","; // добавляем запятую перед элементом, а не после, - // проверяя на первый элемент, это гарантирует, что лишних - // запятых не будет + needed_checks += ","; } needed_checks += val; diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index 9d3d58ba..388f8144 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,29 +1,29 @@ -#include #include #include +#include // Уверен, что это можно сделать значительно качественнее, но дедлайн близко, // поэтому спагетти код >:) void SolveQuadratic(int a, int b, int c) { - if (!a && !b && !c) { + if (a == 0 && b == 0 && c == 0) { std::cout << "infinite solutions"; return; } - if (!a && !b) { + if (a == 0 && b == 0) { std::cout << "no solutions"; return; } std::cout << std::setprecision(6); - if (!a) { - std::cout << (static_cast(-c) / b); + if (a == 0) { + std::cout << static_cast(-c) / b; return; } - if (!b) { + if (b == 0) { if (static_cast(-c) / a < 0) { std::cout << "no solutions"; return; @@ -40,25 +40,21 @@ void SolveQuadratic(int a, int b, int c) { return; } - double d = static_cast(b) * b - 4.0 * a * c; - double x1 = 0.0, x2 = 0.0; + double discriminant = static_cast(b) * b - 4.0 * a * c; + double root1 = 0.0, root2 = 0.0; - if (d < 0) { + if (discriminant == 0) { + std::cout << -b / (2.0 * a); + } + + if (discriminant < 0) { std::cout << "no solutions"; return; } - if (d > 0) { - x1 = ((-b - std::sqrt(d)) / (2.0 * a)); - x2 = ((-b + std::sqrt(d)) / (2.0 * a)); - - if (x1 > x2) { - std::cout << x2 << " " << x1; - } else { - std::cout << x1 << " " << x2; - } - return; - } + root1 = ((-b - std::sqrt(discriminant)) / (2.0 * a)); + root2 = ((-b + std::sqrt(discriminant)) / (2.0 * a)); - std::cout << -b / (2.0 * a); + root1 > root2 ? std::cout << root2 << " " << root1 : + std:: cout << root1 << " " << root2; } diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 64cf032f..9c1d69c7 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,9 +1,8 @@ #include -#include #include double CalculateRMS(double values[], size_t size) { - if (size == 0 || values == NULL) { + if (size == 0 || !values) { return 0.0; } diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index 68b25cef..059cf696 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,14 +1,13 @@ -#include +#include -typedef double(*operations_t)(double, double); +using operations_t = double(*)(double, double); double ApplyOperations(double a, double b, operations_t mathOperations[], size_t size) { if (size == 0 || mathOperations == nullptr) { return 0.0; } - double sum = 0.0; - + double sum = 0.0; for (size_t i = 0; i < size; ++i) { if (mathOperations[i] != nullptr) { sum += mathOperations[i](a, b); 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 fa59bff9..9518214f 100644 --- a/02_week/tasks/last_of_us/last_of_us.cpp +++ b/02_week/tasks/last_of_us/last_of_us.cpp @@ -1,20 +1,11 @@ -#include - typedef bool (*predicate_func_t)(int); const int* FindLastElement(const int* begin, const int* end, predicate_func_t predicate) { - if (begin == nullptr || end == nullptr) { - return end; - } - - if (begin >= end) { + if (!begin || !end || begin >= end) { return end; } - + const int* result = end; - - // begin и end передаются by copy, так что инкремент указателя - // не повлияет на переданный указатель while (begin != end) { if (predicate(*begin)) { result = begin; diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 12b87b36..6479efd5 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,13 +1,7 @@ -#include - +#include const char* FindLongestSubsequence(const char* begin, const char* end, size_t& count) { - if (begin == nullptr || end == nullptr) { - count = 0; - return nullptr; - } - - if (begin >= end) { + if (!begin || !end || begin >= end) { count = 0; return nullptr; } @@ -16,7 +10,7 @@ const char* FindLongestSubsequence(const char* begin, const char* end, size_t& c const char* longestSequenceStart = begin; while (begin != end) { - currSequenseLen++; + ++currSequenseLen; if (*begin != *(begin + 1)) { if (currSequenseLen > count) { diff --git a/02_week/tasks/pretty_array/pretty_array.cpp b/02_week/tasks/pretty_array/pretty_array.cpp index 15895d31..38b89f9b 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,10 +1,9 @@ #include -#include #include void PrintArray(const int* begin, const int* end, int constrainer = 0) { - if (begin == nullptr || end == nullptr) { + if (!begin || !end) { std::cout << "[]" << std::endl; return; } @@ -28,7 +27,7 @@ void PrintArray(const int* begin, const int* end, int constrainer = 0) { } output.append(std::to_string(arr[i])); - charCntr++; + ++charCntr; } output += "]"; diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index ffaf09dc..368908d0 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,4 +1,3 @@ -#include template void SwapPtr(T &ptr1, T &ptr2) { diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index 3a29de14..84b30479 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -6,20 +6,20 @@ struct DataStats { double sd = 0.0; }; -struct DataStats CalculateDataStats(const std::vector &v) { - if (v.empty()) { +struct DataStats CalculateDataStats(const std::vector &values) { + if (values.empty()) { return {0.0, 0.0}; } long sum = 0; long sumSq = 0; - for (auto val : v) { + for (auto val : values) { sum += val; sumSq += static_cast(val) * val; } - auto n = v.size(); + auto n = values.size(); double avg = static_cast(sum) / n; double variance = (sumSq - (static_cast(sum) * sum) / n) / n; diff --git a/03_week/tasks/enum_operators/enum_operators.cpp b/03_week/tasks/enum_operators/enum_operators.cpp index 61599cfc..fe15cc0f 100644 --- a/03_week/tasks/enum_operators/enum_operators.cpp +++ b/03_week/tasks/enum_operators/enum_operators.cpp @@ -1,10 +1,5 @@ -#include #include -#include #include -#include -#include -#include #include enum class CheckFlags : uint8_t { diff --git a/03_week/tasks/minmax/minmax.cpp b/03_week/tasks/minmax/minmax.cpp index c7ddcbce..5f016922 100644 --- a/03_week/tasks/minmax/minmax.cpp +++ b/03_week/tasks/minmax/minmax.cpp @@ -1,16 +1,20 @@ #include +#include #include #include -std::pair::const_iterator, std::vector::const_iterator> MinMax(const std::vector& v) { +using ItMin = std::vector::const_iterator; +using ItMax = std::vector::const_iterator; + +std::pair MinMax(const std::vector& v) { if (v.empty()) { return {v.end(), v.end()}; } auto minIt = v.begin(); auto maxIt = v.end(); - int min = INT_MAX; - int max = INT_MIN; + int min = std::numeric_limits::max(); + int max = std::numeric_limits::min(); for (auto it = v.begin(); it != v.end(); ++it) { if (*it < min) { diff --git a/03_week/tasks/os_overload/os_overload.cpp b/03_week/tasks/os_overload/os_overload.cpp index b62c77e6..8df947b5 100644 --- a/03_week/tasks/os_overload/os_overload.cpp +++ b/03_week/tasks/os_overload/os_overload.cpp @@ -16,15 +16,12 @@ struct Circle { using CircleRegion = std::pair; using CircleRegionList = std::vector; - std::ostream& operator<<(std::ostream& os, const Coord2D& coord) { os << '(' << coord.x << ", " << coord.y << ')'; - return os; } std::ostream& operator<<(std::ostream& os, const Circle& c) { - if (c.radius == 0) { os << "circle[]"; return os; @@ -36,15 +33,7 @@ std::ostream& operator<<(std::ostream& os, const Circle& c) { } std::ostream& operator<<(std::ostream& os, const CircleRegion& r) { - if (r.second == true) { - os << '+'; - } else { - os << '-'; - } - - os << r.first; - - return os; + return os << (r.second == true ? '+' : '-') << r.first; } std::ostream& operator<<(std::ostream& os, const CircleRegionList& lst) { @@ -62,12 +51,12 @@ std::ostream& operator<<(std::ostream& os, const CircleRegionList& lst) { os << ','; } - os << std::endl << '\t' << val; + os << "\n\t" << val; first = false; } - os << std::endl <<"}"; + os << "\n}"; return os; } diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index fe27b102..667350e4 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -1,21 +1,13 @@ -#include #include -#include #include std::vector Range(int from, int to, int step = 1) { std::vector range{}; - if (step == 0) { - return range; - } - - if (step < 0 && from < to) { - return range; - } - - if (step > 0 && from > to) { + if (step == 0 + || step < 0 && from < to + || step > 0 && from > to) { return range; } diff --git a/03_week/tasks/unique/unique.cpp b/03_week/tasks/unique/unique.cpp index bec3950b..9a3f4b5d 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -4,8 +4,6 @@ std::vector Unique(const std::vector& v) { std::vector uniqueElem{}; uniqueElem.reserve(v.size()); - - for (auto val : v) { if (uniqueElem.empty() || (uniqueElem.back() != val)) { uniqueElem.push_back(val); diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 77bdac17..818ea237 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -14,21 +14,21 @@ class Queue { } }; - Queue(std::vector v) : outputV_(v.rbegin(), v.rend()){}; + Queue(std::vector& v) : outputV_(v.rbegin(), v.rend()){}; Queue(std::initializer_list list) : inputV_(list) {}; - Queue(const size_t size) { + Queue(size_t size) { inputV_.reserve(size); outputV_.reserve(size); }; - Queue(const int size) { - inputV_.reserve(size); - outputV_.reserve(size); - }; + // Queue(const int size) { + // inputV_.reserve(size); + // outputV_.reserve(size); + // }; - inline void Push(int val); + void Push(int val); bool Pop(); int& Front(); const int& Front() const; @@ -44,7 +44,7 @@ class Queue { return false; } - return this->GetQueueAsVector() == other.GetQueueAsVector(); + return GetQueueAsVector() == other.GetQueueAsVector(); } bool operator!=(const Queue& other) const { @@ -67,15 +67,15 @@ void Queue::CopyIfOutEmpty() { std::vector Queue::GetQueueAsVector() const { std::vector result; + result.reserve(Size()); std::copy(outputV_.rbegin(), outputV_.rend(), std::back_inserter(result)); - std::copy(inputV_.begin(), inputV_.end(), std::back_inserter(result)); return result; } -inline void Queue::Push(int val) { +void Queue::Push(int val) { inputV_.push_back(val); } @@ -83,11 +83,8 @@ bool Queue::Pop() { if (outputV_.empty() && inputV_.empty()) { return false; } - CopyIfOutEmpty(); - outputV_.pop_back(); - return true; } diff --git a/04_week/tasks/stack/stack.cpp b/04_week/tasks/stack/stack.cpp index 5f9241ed..94d0844a 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -13,7 +13,7 @@ class Stack { void Swap(Stack& other); bool operator==(const Stack& other) const { - return this->stack_ == other.stack_; + return stack_ == other.stack_; } bool operator!=(const Stack& other) const { From 0f8501bf32aadb8d910db88e8e8c72c94186181e Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 4 Feb 2026 17:12:08 +0500 Subject: [PATCH 39/49] review fixes #2 --- 01_week/tasks/quadratic/quadratic.cpp | 3 +- 03_week/tasks/range/range.cpp | 6 +- 04_week/tasks/queue/queue.cpp | 31 ++++++++++- 04_week/tasks/ring_buffer/ring_buffer.cpp | 67 +++++++++++------------ 4 files changed, 67 insertions(+), 40 deletions(-) diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index 388f8144..8a305978 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -44,7 +44,8 @@ void SolveQuadratic(int a, int b, int c) { double root1 = 0.0, root2 = 0.0; if (discriminant == 0) { - std::cout << -b / (2.0 * a); + std::cout << -b / (2.0 * a); + return; } if (discriminant < 0) { diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index 667350e4..41814105 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -5,9 +5,9 @@ std::vector Range(int from, int to, int step = 1) { std::vector range{}; - if (step == 0 - || step < 0 && from < to - || step > 0 && from > to) { + if ((step == 0) + || (step < 0 && from < to) + || (step > 0 && from > to)) { return range; } diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 818ea237..aba9160c 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -44,7 +44,27 @@ class Queue { return false; } - return GetQueueAsVector() == other.GetQueueAsVector(); + if (outputV_.size() == Size() && other.outputV_.size() == other.Size()) { + return outputV_ == other.outputV_; + } + + size_t idx = 0; + + for (int i = outputV_.size() - 1; i >= 0; --i) { + if (outputV_[i] != other.GetElementAt(idx)) { + return false; + } + ++idx; + } + + for (size_t i = 0; i < inputV_.size(); ++i) { + if (inputV_[i] != other.GetElementAt(idx)) { + return false; + } + ++idx; + } + + return true; } bool operator!=(const Queue& other) const { @@ -53,6 +73,7 @@ class Queue { private: void CopyIfOutEmpty(); + int GetElementAt(size_t idx) const; std::vector GetQueueAsVector() const; std::vector inputV_{}; std::vector outputV_{}; @@ -65,6 +86,14 @@ void Queue::CopyIfOutEmpty() { } } +int Queue::GetElementAt(size_t idx) const { + if (idx < outputV_.size()) { + return outputV_[outputV_.size() - 1 - idx]; + } + + return inputV_[idx - outputV_.size()]; +} + std::vector Queue::GetQueueAsVector() const { std::vector result; result.reserve(Size()); diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index 6e798755..db6ec9f7 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -6,10 +6,15 @@ class RingBuffer { public: RingBuffer() : ringBuff_(1), head_(0), tail_(0), size_(0) {} - RingBuffer(size_t capacity) : ringBuff_(capacity > 0 ? capacity : 1), head_(0), tail_(0), size_(0) {} + RingBuffer(size_t capacity) : ringBuff_(capacity > 0 ? capacity : 1), + head_(0), + tail_(0), + size_(0) {} - RingBuffer(size_t capacity, const int iVal) : ringBuff_(capacity > 0 ? capacity : 1, iVal), head_(capacity), tail_(0), - size_(capacity > 0 ? capacity : 1) {} + RingBuffer(size_t capacity, int iVal) : ringBuff_(capacity > 0 ? capacity : 1, iVal), + head_(capacity), + tail_(0), + size_(capacity > 0 ? capacity : 1) {} RingBuffer(std::initializer_list list) : ringBuff_(list), head_(0), tail_(0), size_(list.size()) { if (list.size() == 0) { @@ -35,18 +40,18 @@ class RingBuffer { std::vector Vector() const; int& operator[](size_t idx) { - return ringBuff_[(tail_ + idx) % ringBuff_.size()]; + return ringBuff_[(tail_ + idx) % ringBuff_.capacity()]; } const int& operator[](size_t idx) const { - return ringBuff_[(tail_ + idx) % ringBuff_.size()]; + return ringBuff_[(tail_ + idx) % ringBuff_.capacity()]; } private: std::vector ringBuff_{}; - size_t head_ = 0; - size_t tail_ = 0; - size_t size_ = 0; + size_t head_ = 0; + size_t tail_ = 0; + size_t size_ = 0; }; void RingBuffer::Push(int val) { @@ -60,7 +65,7 @@ void RingBuffer::Push(int val) { ++size_; } else { // аналогично head - tail_ = (tail_ + 1) % ringBuff_.capacity(); + tail_ = (tail_ + 1) % cap; } } @@ -88,14 +93,14 @@ void RingBuffer::Pop() { } bool RingBuffer::TryPop(int& val) { - if (size_ > 0) { - val = ringBuff_[tail_]; - tail_ = (tail_ + 1) % ringBuff_.capacity(); - --size_; - return true; + if (size_ == 0) { + return false; } - - return false; + + val = ringBuff_[tail_]; + tail_ = (tail_ + 1) % ringBuff_.capacity(); + --size_; + return true; } int& RingBuffer::Front() { @@ -147,34 +152,26 @@ void RingBuffer::Clear() { void RingBuffer::Resize(size_t newSize) { if (newSize == 0) { - ++newSize; - } - - if (newSize == ringBuff_.size()) { + newSize = 1; + } + + if (newSize == ringBuff_.capacity()) { return; } - size_t sz = std::min(size_, newSize); - std::vector tempV; - tempV.reserve(sz); + std::vector tempV(newSize); - for (size_t i = 0; i < sz; ++i) { - tempV.push_back(ringBuff_[(head_ - 1 - i + ringBuff_.size()) % ringBuff_.size()]); + size_t elemsToCopy = std::min(size_, newSize); + for (size_t i = 0; i < elemsToCopy; ++i) { + tempV[i] = ringBuff_[(tail_ + size_ - elemsToCopy + i) % ringBuff_.capacity()]; } - std::reverse(tempV.begin(), tempV.end()); - ringBuff_.resize(newSize); + ringBuff_.swap(tempV); - for (size_t i = 0; i < sz; ++i) { - ringBuff_[i] = tempV[i]; - } - - ringBuff_.shrink_to_fit(); - tail_ = 0; - head_ = sz; - size_ = sz; + head_ = elemsToCopy; + size_ = elemsToCopy; } std::vector RingBuffer::Vector() const { From fedc8a65bf46f81830242d14845682255ded26e1 Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 5 Feb 2026 10:04:00 +0500 Subject: [PATCH 40/49] =?UTF-8?q?review=20fixes=20=E2=84=963?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 04_week/tasks/phasor/phasor.cpp | 52 +++++++++++------------ 04_week/tasks/ring_buffer/ring_buffer.cpp | 15 ++++--- 2 files changed, 33 insertions(+), 34 deletions(-) diff --git a/04_week/tasks/phasor/phasor.cpp b/04_week/tasks/phasor/phasor.cpp index 3d5874fd..f9fd823c 100644 --- a/04_week/tasks/phasor/phasor.cpp +++ b/04_week/tasks/phasor/phasor.cpp @@ -7,13 +7,12 @@ namespace { constexpr double EPS_ = 1e-12; } - double DegToRad(double deg) { return deg * M_PI / 180.0; } double RadToDeg(double rad){ - return rad * 180 / M_PI; + return rad * 180.0 / M_PI; } double NormalizePhase(double phase) { @@ -38,22 +37,22 @@ struct AlgTag {}; class Phasor { public: Phasor() = default; - Phasor(double A, double rad) { - if (A < 0) { - A = -A; + Phasor(double magnitude, double rad) { + if (magnitude < 0) { + magnitude = -magnitude; rad += M_PI; } rad = NormalizePhase(rad); - real_ = A * std::cos(rad); - imag_ = A * std::sin(rad); + real_ = magnitude * std::cos(rad); + imag_ = magnitude * std::sin(rad); }; - Phasor(double A, double rad, ExpTag) : Phasor(A, rad) {}; - Phasor(double A, double deg, DegTag) : Phasor(A, DegToRad(deg)) {}; + Phasor(double magnitude, double rad, ExpTag) : Phasor(magnitude, rad) {}; + Phasor(double magnitude, double deg, DegTag) : Phasor(magnitude, DegToRad(deg)) {}; Phasor(double real, double imag, AlgTag) : real_(real), imag_(imag) {}; - void SetPolar(double A, double rad); + void SetPolar(double magnitude, double rad); void SetCartesian(double real, double imag); double Magnitude() const; double Phase() const; @@ -132,17 +131,17 @@ Phasor operator-(const Phasor& lhs, const Phasor& rhs) { } Phasor operator*(const Phasor& lhs, const Phasor& rhs) { - double A = lhs.Magnitude() * rhs.Magnitude(); + double magnitude = lhs.Magnitude() * rhs.Magnitude(); double rad = lhs.Phase() + rhs.Phase(); - return Phasor(A, NormalizePhase(rad)); + return Phasor(magnitude, NormalizePhase(rad)); } Phasor operator/(const Phasor& lhs, const Phasor& rhs) { - double A = lhs.Magnitude() / rhs.Magnitude(); + double magnitude = lhs.Magnitude() / rhs.Magnitude(); double rad = lhs.Phase() - rhs.Phase(); - return Phasor(A, NormalizePhase(rad)); + return Phasor(magnitude, NormalizePhase(rad)); } bool operator==(const Phasor& lhs, const Phasor& rhs) { @@ -159,8 +158,8 @@ Phasor operator+(const Phasor& lhs, double rhs) { } // Сложение коммутативно -Phasor operator+(double rhs, const Phasor& lhs) { - return Phasor(lhs.Real() + rhs, lhs.Imag(), AlgTag{}); +Phasor operator+(double lhs, const Phasor& rhs) { + return rhs + lhs; } Phasor operator-(const Phasor& lhs, double rhs) { @@ -171,14 +170,13 @@ Phasor operator-(double lhs, const Phasor& rhs) { return (lhs + (-rhs)); } - Phasor operator*(const Phasor& lhs, double rhs) { return Phasor(lhs.Real() * rhs, lhs.Imag() * rhs, AlgTag{}); } // Умножение тоже коммутативно -Phasor operator*(double rhs, const Phasor& lhs) { - return Phasor(lhs.Real() * rhs, lhs.Imag() * rhs, AlgTag{}); +Phasor operator*(double lhs, const Phasor& rhs) { + return rhs * lhs; } Phasor operator/(const Phasor& lhs, double rhs) { @@ -186,9 +184,9 @@ Phasor operator/(const Phasor& lhs, double rhs) { } Phasor operator/(double lhs, const Phasor& rhs) { - double A = std::abs(lhs) / rhs.Magnitude(); + double magnitude = std::abs(lhs) / rhs.Magnitude(); double rad = ((lhs >= 0) ? 0.0 : M_PI) - rhs.Phase(); - return Phasor(A, NormalizePhase(rad)); + return Phasor(magnitude, NormalizePhase(rad)); } std::ostream& operator<<(std::ostream& os, const Phasor& p) { @@ -198,8 +196,8 @@ std::ostream& operator<<(std::ostream& os, const Phasor& p) { return os; } -void Phasor::SetPolar(double A, double rad) { - *this = Phasor(A, rad); +void Phasor::SetPolar(double magnitude, double rad) { + *this = Phasor(magnitude, rad); } void Phasor::SetCartesian(double real, double imag) { @@ -251,10 +249,10 @@ Phasor MakePhasorCartesian(double real, double imag) { return Phasor(real, imag, AlgTag{}); } -Phasor MakePhasorPolar(double A, double rad) { - return Phasor(A, rad); +Phasor MakePhasorPolar(double magnitude, double rad) { + return Phasor(magnitude, rad); } -Phasor MakePhasorPolarDeg(double A, double deg) { - return Phasor(A, deg, DegTag{}); +Phasor MakePhasorPolarDeg(double magnitude, double deg) { + return Phasor(magnitude, deg, DegTag{}); } diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index db6ec9f7..4de57744 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -70,15 +70,15 @@ void RingBuffer::Push(int val) { } bool RingBuffer::TryPush(int val) { - size_t cap = ringBuff_.capacity(); + size_t capacity = ringBuff_.capacity(); - if (size_ == cap) { + if (size_ == capacity) { return false; } ringBuff_[head_] = val; // при head = buff.capacity(), head снова станет = 0 - head_ = (head_ + 1) % cap; + head_ = (head_ + 1) % capacity; ++size_; @@ -175,12 +175,13 @@ void RingBuffer::Resize(size_t newSize) { } std::vector RingBuffer::Vector() const { - std::vector v; - v.reserve(size_); + std::vector rb_as_vector; + size_t capacity = ringBuff_.capacity(); + rb_as_vector.reserve(capacity); for (size_t i = 0; i < size_; ++i) { - v.push_back(ringBuff_[(tail_ + i) % ringBuff_.size()]); + rb_as_vector.push_back(ringBuff_[(tail_ + i) % capacity]); } - return v; + return rb_as_vector; } From d224fa12e428cf88ac65d9dbf82429268642693b Mon Sep 17 00:00:00 2001 From: Radiy Date: Sun, 8 Feb 2026 17:58:21 +0500 Subject: [PATCH 41/49] add (solution): add tracer task --- 05_week/tasks/tracer/tracer.cpp | 112 +++++++++++++++++++++++++++++++- 1 file changed, 110 insertions(+), 2 deletions(-) diff --git a/05_week/tasks/tracer/tracer.cpp b/05_week/tasks/tracer/tracer.cpp index 2ccfb417..7a9544c8 100644 --- a/05_week/tasks/tracer/tracer.cpp +++ b/05_week/tasks/tracer/tracer.cpp @@ -1,6 +1,114 @@ #include - class Tracer { +public: + static size_t count; + static size_t default_ctor; + static size_t str_ctor; + static size_t copy_ctor; + static size_t move_ctor; + static size_t copy_assign; + static size_t move_assign; + static size_t dtor; + static size_t alive; + + Tracer() { + ++count; + ++default_ctor; + ++alive; + id = count; + name = "obj_" + std::to_string(id); + } + + Tracer(const std::string& objName) { + ++count; + ++str_ctor; + ++alive; + id = count; + name = objName + '_' + std::to_string(id); + } + + Tracer(const Tracer& other) { + ++count; + ++copy_ctor; + ++alive; + id = count; + name = other.name; + } + + Tracer(Tracer&& other) noexcept { + ++count; + ++move_ctor; + ++alive; + id = count; + name = std::move(other.name); + } + + Tracer& operator=(const Tracer& other) { + if (other.id == id ) { + return *this; + } + + ++copy_assign; + name = other.name; + return *this; + } + + Tracer& operator=(Tracer&& other) noexcept { + if (other.id == id) { + return *this; + } + + ++move_assign; + name = std::move(other.name); + return *this; + } + + ~Tracer() { + ++dtor; + --alive; + } + + size_t Id(); + const std::string& Name() const; + const char* Data() const; + static void ResetStats(); + +private: + size_t id; + std::string name; +}; + +size_t Tracer::count = 0; +size_t Tracer::default_ctor = 0; +size_t Tracer::str_ctor = 0; +size_t Tracer::copy_ctor = 0; +size_t Tracer::move_ctor = 0; +size_t Tracer::copy_assign = 0; +size_t Tracer::move_assign = 0; +size_t Tracer::dtor = 0; +size_t Tracer::alive = 0; + +size_t Tracer::Id() { + return id; +} + +const std::string& Tracer::Name() const { + return name; +} + +const char* Tracer::Data() const { + return name.data(); +} -}; \ No newline at end of file +void Tracer::ResetStats() { + count = 0; + default_ctor = 0; + str_ctor = 0; + copy_ctor = 0; + move_ctor = 0; + copy_assign = 0; + move_assign = 0; + dtor = 0; + alive = 0; +} From 2bf0972d87a7fde1f3de64eb0ca6234bb7ac4baa Mon Sep 17 00:00:00 2001 From: Radiy Date: Sun, 8 Feb 2026 21:33:31 +0500 Subject: [PATCH 42/49] add (solution): add string_view task --- 05_week/tasks/string_view/string_view.cpp | 175 +++++++++++++++++++++- 05_week/tasks/string_view/test.cpp | 2 +- 05_week/tasks/tracer/tracer.cpp | 34 ++--- 3 files changed, 192 insertions(+), 19 deletions(-) diff --git a/05_week/tasks/string_view/string_view.cpp b/05_week/tasks/string_view/string_view.cpp index 438c4536..877582c9 100644 --- a/05_week/tasks/string_view/string_view.cpp +++ b/05_week/tasks/string_view/string_view.cpp @@ -1,7 +1,180 @@ #include +#include +#include #include +#include class StringView { +public: + inline static size_t npos = std::numeric_limits::max(); + + StringView() = default; + + StringView(const std::string& str, size_t start = 0, size_t len = npos) { + if (start > str.size() || str.empty()) { + return; + } -}; \ No newline at end of file + if (len == npos || start + len > str.size()) { + len = str.size() - start; + } + + begin_ = str.data() + start; + end_ = begin_ + len; + }; + + StringView(const std::string&& str, size_t start = 0, size_t len = npos) { + if (start > str.size() || str.empty()) { + return; + } + + tempStr_ = std::move(str); + + + if (len == npos || start + len > tempStr_->size()) { + len = tempStr_->size() - start; + } + + begin_ = tempStr_->data() + start; + end_ = begin_ + len; + }; + + StringView(const char* str) : begin_(str ? str : nullptr), end_(str ? str + std::strlen(str) : nullptr) {} + + StringView(const char* str, size_t len) { + if (!str) { + return; + } + + size_t strLen = std::strlen(str); + if (len > strLen) { + len = strLen; + } + + begin_ = str; + end_ = str + len; + } + + const char& operator[](size_t idx) const { + return begin_[idx]; + } + + const char* Data() const; + const char& Front() const; + const char& Back() const; + size_t Size() const; + size_t Length() const; + bool Empty() const; + int Compare(StringView& str) const; + void RemovePrefix(size_t len); + void RemoveSuffix(size_t len); + StringView Substr(size_t start, size_t len) const; + size_t Find(char symbol, size_t start) const; + size_t Find(StringView str, size_t start) const; + std::string ToString() const; + +private: + std::optional tempStr_; + const char* begin_ = nullptr; + const char* end_ = nullptr; +}; + + +bool operator==(StringView& lhs, StringView& rhs) { + return std::strcmp(lhs.Data(), rhs.Data()) == 0; +} + +const char* StringView::Data() const { + return begin_; +} + +const char& StringView::Front() const { + return *begin_; +} + +const char& StringView::Back() const { + return *(end_ - 1); +} + +size_t StringView::Size() const { + return end_ - begin_; +} + +size_t StringView::Length() const { + return Size(); +} + +bool StringView::Empty() const { + if (begin_ == end_ || begin_ == nullptr) { + return true; + } + + return false; +} + +int StringView::Compare(StringView& str) const { + return std::strcmp(begin_, str.begin_); +} + +void StringView::RemovePrefix(size_t len) { + if (begin_ + len >= end_) { + begin_ = end_; + return; + } + + begin_ += len; +} + +void StringView::RemoveSuffix(size_t len) { + if (end_ - len <= begin_) { + end_ = begin_; + return; + } + + end_ -= len; +} + +StringView StringView::Substr(size_t start = 0, size_t len = 0) const { + if (start > Size() || Empty()) { + return StringView(); + } + + if (len == 0) { + return StringView(begin_ + start); + } + + return StringView(begin_ + start, len); +} + +size_t StringView::Find(char symbol, size_t start = 0) const { + if (start > Size() || Empty()) { + return npos; + } + + const char* pos = std::strchr(begin_ + start, symbol); + + if (!pos) { + return npos; + } + + return pos - begin_; +} + +size_t StringView::Find(StringView str, size_t start = 0) const { + if (start > Size() || str.Size() > Size() || Empty()) { + return npos; + } + + const char* pos = std::strstr(begin_ + start, str.begin_); + + if (!pos) { + return npos; + } + + return pos - begin_; +} + +std::string StringView::ToString() const { + return std::string(begin_, Size()); +} diff --git a/05_week/tasks/string_view/test.cpp b/05_week/tasks/string_view/test.cpp index b43d7bca..84d73a17 100644 --- a/05_week/tasks/string_view/test.cpp +++ b/05_week/tasks/string_view/test.cpp @@ -362,4 +362,4 @@ TEST(StringViewTest, PerformanceCharacteristics) { std::string copy = sv.ToString(); EXPECT_EQ(copy.size(), 1000000); -} \ No newline at end of file +} diff --git a/05_week/tasks/tracer/tracer.cpp b/05_week/tasks/tracer/tracer.cpp index 7a9544c8..0e3869c0 100644 --- a/05_week/tasks/tracer/tracer.cpp +++ b/05_week/tasks/tracer/tracer.cpp @@ -16,51 +16,51 @@ class Tracer { ++count; ++default_ctor; ++alive; - id = count; - name = "obj_" + std::to_string(id); + id_ = count; + name_ = "obj_" + std::to_string(id_); } Tracer(const std::string& objName) { ++count; ++str_ctor; ++alive; - id = count; - name = objName + '_' + std::to_string(id); + id_ = count; + name_ = objName + '_' + std::to_string(id_); } Tracer(const Tracer& other) { ++count; ++copy_ctor; ++alive; - id = count; - name = other.name; + id_ = count; + name_ = other.name_; } Tracer(Tracer&& other) noexcept { ++count; ++move_ctor; ++alive; - id = count; - name = std::move(other.name); + id_ = count; + name_ = std::move(other.name_); } Tracer& operator=(const Tracer& other) { - if (other.id == id ) { + if (other.id_ == id_ ) { return *this; } ++copy_assign; - name = other.name; + name_ = other.name_; return *this; } Tracer& operator=(Tracer&& other) noexcept { - if (other.id == id) { + if (other.id_ == id_) { return *this; } ++move_assign; - name = std::move(other.name); + name_ = std::move(other.name_); return *this; } @@ -75,8 +75,8 @@ class Tracer { static void ResetStats(); private: - size_t id; - std::string name; + size_t id_; + std::string name_; }; size_t Tracer::count = 0; @@ -90,15 +90,15 @@ size_t Tracer::dtor = 0; size_t Tracer::alive = 0; size_t Tracer::Id() { - return id; + return id_; } const std::string& Tracer::Name() const { - return name; + return name_; } const char* Tracer::Data() const { - return name.data(); + return name_.data(); } void Tracer::ResetStats() { From 5202c5458a7e1c658861fe85fcfebc50d1c88852 Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 11 Feb 2026 18:02:14 +0500 Subject: [PATCH 43/49] wip cow_string task --- 05_week/tasks/cow_string/cow_string.cpp | 125 ++++++++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/05_week/tasks/cow_string/cow_string.cpp b/05_week/tasks/cow_string/cow_string.cpp index 34d59738..3f178233 100644 --- a/05_week/tasks/cow_string/cow_string.cpp +++ b/05_week/tasks/cow_string/cow_string.cpp @@ -1,6 +1,131 @@ #include +#include #include +namespace { + // Не уверен, что определение структуры нужно заносить + // в безымянный namespacе. + struct CowStringData { + char* data = nullptr; + size_t size = 0; + size_t refCount = 1; + + CowStringData() = default; + + CowStringData(const char* str) { + size = strlen(str); + data = new char[size + 1]; + std::strcpy(data, str); + refCount = 1; + } + + CowStringData(const std::string& str) { + size = str.size(); + data = new char[size + 1]; + std::strcpy(data, str.c_str()); + refCount = 1; + } + + ~CowStringData() { + delete[] data; + } + }; +} + class CowString { +public: + CowString() : cowString_(new CowStringData) {} + + CowString(const char* str) : cowString_(new CowStringData(str)) {} + + CowString(const std::string& str) : cowString_(new CowStringData(str)) {} + + CowString(const CowString& other) { + cowString_ = other.cowString_; + if (cowString_) { + ++cowString_->refCount; + } + } + + CowString(CowString&& other) { + cowString_ = other.cowString_; + other.cowString_ = nullptr; + } + + ~CowString() { + DecreaseRefCount(); + } + + CowString& operator=(CowString& other) { + if (this == &other) { + return *this; + } + + DecreaseRefCount(); + + cowString_ = other.cowString_; + if (cowString_) { + ++cowString_->refCount; + } + + return *this; + } + CowString& operator=(CowString&& other) { + if (this == &other) { + return *this; + } + + DecreaseRefCount(); + + cowString_ = other.cowString_; + other.cowString_ = nullptr; + + return *this; + } + + const char& operator[](size_t idx) const { + return cowString_->data[idx]; + } + + char& operator[](size_t idx) { + if (cowString_->refCount > 1) { + MakeDeepCopy(); + } + + return cowString_->data[idx]; + } + + size_t Size() const; + const char* ToStr() const; + const std::string ToString() const; + void Append(); + CowString Substr(size_t start = 0, size_t len = std::numeric_limits::max()); + void Clear(); + + +private: + CowStringData* cowString_ = nullptr; + + void DecreaseRefCount(); + void MakeDeepCopy(); }; + +void CowString::DecreaseRefCount() { + if (cowString_ && --cowString_->refCount == 0) { + delete cowString_; + } +} + +void CowString::MakeDeepCopy() { + CowStringData* deep_copy = new CowStringData(cowString_->data); + DecreaseRefCount(); + cowString_ = deep_copy; +} + +size_t CowString::Size() const { + return cowString_->size; +} + +const char* CowString::ToStr() const { +} From 5f362027905c713b6f033c751fc7be549e64aa11 Mon Sep 17 00:00:00 2001 From: Radiy Date: Wed, 11 Feb 2026 22:33:48 +0500 Subject: [PATCH 44/49] =?UTF-8?q?wip=20=E2=84=962=20cow=5Fstring=20task?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 05_week/tasks/cow_string/cow_string.cpp | 218 +++++++++++++++++++----- 1 file changed, 179 insertions(+), 39 deletions(-) diff --git a/05_week/tasks/cow_string/cow_string.cpp b/05_week/tasks/cow_string/cow_string.cpp index 3f178233..48d90bc8 100644 --- a/05_week/tasks/cow_string/cow_string.cpp +++ b/05_week/tasks/cow_string/cow_string.cpp @@ -2,38 +2,36 @@ #include #include -namespace { - // Не уверен, что определение структуры нужно заносить - // в безымянный namespacе. - struct CowStringData { - char* data = nullptr; - size_t size = 0; - size_t refCount = 1; - - CowStringData() = default; - - CowStringData(const char* str) { - size = strlen(str); - data = new char[size + 1]; - std::strcpy(data, str); - refCount = 1; - } +struct CowStringData { + char* data = nullptr; + size_t size = 0; + size_t refCount = 1; - CowStringData(const std::string& str) { - size = str.size(); - data = new char[size + 1]; - std::strcpy(data, str.c_str()); - refCount = 1; - } + CowStringData() : data(new char[1]{'\0'}) {} - ~CowStringData() { - delete[] data; - } - }; -} + CowStringData(const char* str) { + size = strlen(str); + data = new char[size + 1]; + std::strcpy(data, str); + refCount = 1; + } + + CowStringData(const std::string& str) { + size = str.size(); + data = new char[size + 1]; + std::strcpy(data, str.c_str()); + refCount = 1; + } + + ~CowStringData() { + delete[] data; + } +}; class CowString { public: + inline static size_t npos = std::numeric_limits::max(); + CowString() : cowString_(new CowStringData) {} CowString(const char* str) : cowString_(new CowStringData(str)) {} @@ -47,16 +45,15 @@ class CowString { } } - CowString(CowString&& other) { - cowString_ = other.cowString_; - other.cowString_ = nullptr; + CowString(CowString&& other) : cowString_(other.cowString_) { + other.cowString_ = new CowStringData; } ~CowString() { DecreaseRefCount(); } - CowString& operator=(CowString& other) { + CowString& operator=(const CowString& other) { if (this == &other) { return *this; } @@ -79,7 +76,7 @@ class CowString { DecreaseRefCount(); cowString_ = other.cowString_; - other.cowString_ = nullptr; + other.cowString_ = new CowStringData; return *this; } @@ -88,6 +85,10 @@ class CowString { return cowString_->data[idx]; } + operator const char*() const { + return cowString_->data; + } + char& operator[](size_t idx) { if (cowString_->refCount > 1) { MakeDeepCopy(); @@ -97,13 +98,16 @@ class CowString { } size_t Size() const; - const char* ToStr() const; - const std::string ToString() const; - void Append(); - CowString Substr(size_t start = 0, size_t len = std::numeric_limits::max()); + bool Empty() const; + const char* ToCstr() const; + std::string ToString() const; + size_t Find(char symbol, size_t start) const; + size_t Find(const char* str, size_t start) const; + CowString& Append(const char* str); + CowString& Append(const std::string& str); + CowString Substr(size_t start, size_t len); void Clear(); - - + private: CowStringData* cowString_ = nullptr; @@ -123,9 +127,145 @@ void CowString::MakeDeepCopy() { cowString_ = deep_copy; } +bool operator==(const CowString& lhs, const std::string& rhs) { + return std::strcmp(lhs.ToCstr(), rhs.c_str()) == 0; +} + size_t CowString::Size() const { return cowString_->size; } -const char* CowString::ToStr() const { +bool CowString::Empty() const { + return cowString_->size == 0; +} + +const char* CowString::ToCstr() const { + return cowString_->data; +} + +std::string CowString::ToString() const { + return std::string(cowString_->data, cowString_->size); +} + +size_t CowString::Find(char symbol, size_t start = 0) const { + if (start > Size() || Empty()) { + return npos; + } + + const char* pos = std::strchr(cowString_->data + start, symbol); + + if (!pos) { + return npos; + } + + return pos - cowString_->data; +} + +size_t CowString::Find(const char* str, size_t start = 0) const { + if (start > Size() || std::strlen(str) > Size() || Empty()) { + return npos; + } + + const char* pos = std::strstr(cowString_->data + start, str); + + if (!pos) { + return npos; + } + + return pos - cowString_->data; +} + +CowString& CowString::Append(const char* str) { + if (!str) { + return *this; + } + + if (!cowString_) { + cowString_ = new CowStringData(str); + return *this; + } + + if (cowString_->refCount > 1) { + MakeDeepCopy(); + } + + size_t newSize = cowString_->size + std::strlen(str); + char* newData = new char[newSize + 1]; + + if (cowString_->data) { + std::strcpy(newData, cowString_->data); + } + std::strcat(newData, str); + + delete[] cowString_->data; + cowString_->data = newData; + cowString_->size = newSize; + return *this; +} + +CowString& CowString::Append(const std::string& str) { + if (str.empty()) { + return *this; + } + + if (!cowString_) { + cowString_ = new CowStringData(str); + return *this; + } + + if (cowString_->refCount > 1) { + MakeDeepCopy(); + } + + size_t newSize = cowString_->size + str.size(); + char* newData = new char[newSize + 1]; + + if (cowString_->data) { + std::strcpy(newData, cowString_->data); + } + std::strcat(newData, str.c_str()); + + delete[] cowString_->data; + cowString_->data = newData; + cowString_->size = newSize; + return *this; +} + +CowString CowString::Substr(size_t start = 0, size_t len = npos) { + if (start == 0 && len == npos) { + return CowString(*this); + } + + if (len > cowString_->size) { + len = cowString_->size; + } + + size_t substrSize = len - start; + + char* subStr = new char[substrSize + 1]; + std::strncpy(subStr, &cowString_->data[start], substrSize); + subStr[substrSize] = '\0'; + + CowString subCowStr; + delete[] subCowStr.cowString_->data; + subCowStr.cowString_->data = subStr; + subCowStr.cowString_->size = substrSize; + return subCowStr; +} + +void CowString::Clear() { + if (!cowString_) { + cowString_ = new CowStringData; + return; + } + + if (cowString_->refCount == 1) { + delete cowString_; + cowString_ = new CowStringData; + return; + } + + DecreaseRefCount(); + + cowString_ = new CowStringData; } From 3f3d8e06e0695cae3a539a5a7c9ad20bc0e7fe0b Mon Sep 17 00:00:00 2001 From: Radiy Date: Thu, 12 Feb 2026 12:06:17 +0500 Subject: [PATCH 45/49] add (solution): add cow_string task --- 05_week/tasks/cow_string/cow_string.cpp | 13 ++++++++----- 05_week/tasks/string_view/string_view.cpp | 5 ++--- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/05_week/tasks/cow_string/cow_string.cpp b/05_week/tasks/cow_string/cow_string.cpp index 48d90bc8..0807e3c1 100644 --- a/05_week/tasks/cow_string/cow_string.cpp +++ b/05_week/tasks/cow_string/cow_string.cpp @@ -38,8 +38,7 @@ class CowString { CowString(const std::string& str) : cowString_(new CowStringData(str)) {} - CowString(const CowString& other) { - cowString_ = other.cowString_; + CowString(const CowString& other) : cowString_(other.cowString_){ if (cowString_) { ++cowString_->refCount; } @@ -176,7 +175,7 @@ size_t CowString::Find(const char* str, size_t start = 0) const { } CowString& CowString::Append(const char* str) { - if (!str) { + if (!str || str[0] == '\0') { return *this; } @@ -236,14 +235,18 @@ CowString CowString::Substr(size_t start = 0, size_t len = npos) { return CowString(*this); } + if (start > cowString_->size) { + return CowString(); + } + if (len > cowString_->size) { len = cowString_->size; } - size_t substrSize = len - start; + size_t substrSize = std::min(len, cowString_->size - start); char* subStr = new char[substrSize + 1]; - std::strncpy(subStr, &cowString_->data[start], substrSize); + std::strncpy(subStr, cowString_->data + start, substrSize); subStr[substrSize] = '\0'; CowString subCowStr; diff --git a/05_week/tasks/string_view/string_view.cpp b/05_week/tasks/string_view/string_view.cpp index 877582c9..2781bfd6 100644 --- a/05_week/tasks/string_view/string_view.cpp +++ b/05_week/tasks/string_view/string_view.cpp @@ -31,7 +31,6 @@ class StringView { tempStr_ = std::move(str); - if (len == npos || start + len > tempStr_->size()) { len = tempStr_->size() - start; } @@ -71,7 +70,7 @@ class StringView { void RemoveSuffix(size_t len); StringView Substr(size_t start, size_t len) const; size_t Find(char symbol, size_t start) const; - size_t Find(StringView str, size_t start) const; + size_t Find(const StringView& str, size_t start) const; std::string ToString() const; private: @@ -161,7 +160,7 @@ size_t StringView::Find(char symbol, size_t start = 0) const { return pos - begin_; } -size_t StringView::Find(StringView str, size_t start = 0) const { +size_t StringView::Find(const StringView& str, size_t start = 0) const { if (start > Size() || str.Size() > Size() || Empty()) { return npos; } From a5b774325d32f4a07a7812368e28ee49a4ad6930 Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 13 Feb 2026 12:09:28 +0500 Subject: [PATCH 46/49] add (refactoring): add cow_string task, add string_view task --- 05_week/tasks/cow_string/cow_string.cpp | 22 +++++++++++++++------- 05_week/tasks/string_view/string_view.cpp | 16 ---------------- 2 files changed, 15 insertions(+), 23 deletions(-) diff --git a/05_week/tasks/cow_string/cow_string.cpp b/05_week/tasks/cow_string/cow_string.cpp index 0807e3c1..1c64b118 100644 --- a/05_week/tasks/cow_string/cow_string.cpp +++ b/05_week/tasks/cow_string/cow_string.cpp @@ -7,7 +7,7 @@ struct CowStringData { size_t size = 0; size_t refCount = 1; - CowStringData() : data(new char[1]{'\0'}) {} + CowStringData() = default; CowStringData(const char* str) { size = strlen(str); @@ -25,6 +25,7 @@ struct CowStringData { ~CowStringData() { delete[] data; + data = nullptr; } }; @@ -139,11 +140,12 @@ bool CowString::Empty() const { } const char* CowString::ToCstr() const { - return cowString_->data; + return cowString_->data ? cowString_->data : ""; } std::string CowString::ToString() const { - return std::string(cowString_->data, cowString_->size); + return cowString_->data ? std::string(cowString_->data, cowString_->size) + : ""; } size_t CowString::Find(char symbol, size_t start = 0) const { @@ -188,13 +190,19 @@ CowString& CowString::Append(const char* str) { MakeDeepCopy(); } - size_t newSize = cowString_->size + std::strlen(str); + size_t newStrSize = std::strlen(str); + size_t newSize = cowString_->size + newStrSize; char* newData = new char[newSize + 1]; + size_t offset = 0; + + // memcpy чтобы не проверять на '\0' и избежать ошибки + // c strcat, когда data = nullptr if (cowString_->data) { - std::strcpy(newData, cowString_->data); + std::memcpy(newData, cowString_->data, cowString_->size); + offset = cowString_->size; } - std::strcat(newData, str); + std::memcpy(newData + offset, str, newStrSize + 1); delete[] cowString_->data; cowString_->data = newData; @@ -235,7 +243,7 @@ CowString CowString::Substr(size_t start = 0, size_t len = npos) { return CowString(*this); } - if (start > cowString_->size) { + if (start > cowString_->size || !cowString_->data) { return CowString(); } diff --git a/05_week/tasks/string_view/string_view.cpp b/05_week/tasks/string_view/string_view.cpp index 2781bfd6..e8f1fbba 100644 --- a/05_week/tasks/string_view/string_view.cpp +++ b/05_week/tasks/string_view/string_view.cpp @@ -24,21 +24,6 @@ class StringView { end_ = begin_ + len; }; - StringView(const std::string&& str, size_t start = 0, size_t len = npos) { - if (start > str.size() || str.empty()) { - return; - } - - tempStr_ = std::move(str); - - if (len == npos || start + len > tempStr_->size()) { - len = tempStr_->size() - start; - } - - begin_ = tempStr_->data() + start; - end_ = begin_ + len; - }; - StringView(const char* str) : begin_(str ? str : nullptr), end_(str ? str + std::strlen(str) : nullptr) {} StringView(const char* str, size_t len) { @@ -74,7 +59,6 @@ class StringView { std::string ToString() const; private: - std::optional tempStr_; const char* begin_ = nullptr; const char* end_ = nullptr; }; From 23296e37ecf42b2af087dabcc3858b7562a0f192 Mon Sep 17 00:00:00 2001 From: Radiy Date: Fri, 13 Feb 2026 17:05:55 +0500 Subject: [PATCH 47/49] =?UTF-8?q?wip=20=E2=84=961=20simple=5Fvector=20task?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 05_week/tasks/simple_vector/simple_vector.cpp | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/05_week/tasks/simple_vector/simple_vector.cpp b/05_week/tasks/simple_vector/simple_vector.cpp index 9b2ea971..15591a9c 100644 --- a/05_week/tasks/simple_vector/simple_vector.cpp +++ b/05_week/tasks/simple_vector/simple_vector.cpp @@ -1,5 +1,65 @@ - +#include +#include +#include class SimpleVector { +public: + SimpleVector() = default; + + SimpleVector(size_t size) : begin_(new int[size]{0}), end_(begin_ + size), capacity_(end_) {} + + SimpleVector(std::initializer_list list) : begin_(new int[list.size()]), + end_(std::copy(list.begin(), list.end(), begin_)), + capacity_(end_) {} + + SimpleVector(const SimpleVector& other) : begin_(new int[other.Size()]), + end_(std::copy(other.begin_, other.end_, begin_)), + capacity_(other.end_) {} + + SimpleVector(SimpleVector&& other) : begin_(other.begin_), end_(other.end_), capacity_(other.capacity_) { + other.begin_ = nullptr; + other.end_ = nullptr; + other.capacity_ = nullptr; + } + + ~SimpleVector() { + delete [] begin_; + begin_ = end_ = capacity_ = nullptr; + } + + SimpleVector& operator=(const SimpleVector& other) { + begin_ = new int[other.Size()]; + end_ = std::copy(other.begin_, other.end_, begin_); + capacity_ = end_; + return *this; + } + + SimpleVector& operator=(SimpleVector&& other) { + begin_ = other.begin_; + end_ = other.end_; + capacity_ = other.capacity_; + other.begin_ = nullptr; + other.end_ = nullptr; + other.capacity_ = nullptr; + return *this; + } + + int& operator[](size_t idx){ + return begin_[idx]; + } -}; \ No newline at end of file + void Swap(SimpleVector& other); + size_t Size() const noexcept; + size_t Capacity() const noexcept; + bool Empty() const noexcept; + const int* Data() const; + void PushBack(int value); + void PopBack(); + + + +private: + int* begin_ = nullptr; + int* end_ = nullptr; + int* capacity_ = nullptr; +}; From 826f2d35ac6b19f8450d480d405b65ee9411debe Mon Sep 17 00:00:00 2001 From: Radiy Date: Sat, 14 Feb 2026 16:46:00 +0500 Subject: [PATCH 48/49] add (solution): add simple_vector task --- 05_week/tasks/simple_vector/simple_vector.cpp | 243 +++++++++++++++++- 1 file changed, 234 insertions(+), 9 deletions(-) diff --git a/05_week/tasks/simple_vector/simple_vector.cpp b/05_week/tasks/simple_vector/simple_vector.cpp index 15591a9c..8894635f 100644 --- a/05_week/tasks/simple_vector/simple_vector.cpp +++ b/05_week/tasks/simple_vector/simple_vector.cpp @@ -1,5 +1,6 @@ #include #include +#include #include class SimpleVector { @@ -8,15 +9,32 @@ class SimpleVector { SimpleVector(size_t size) : begin_(new int[size]{0}), end_(begin_ + size), capacity_(end_) {} + SimpleVector(size_t size, int value) : begin_(new int[size]), end_(begin_ + size), capacity_(end_) { + std::fill(begin_, end_, value); + } + SimpleVector(std::initializer_list list) : begin_(new int[list.size()]), end_(std::copy(list.begin(), list.end(), begin_)), capacity_(end_) {} - SimpleVector(const SimpleVector& other) : begin_(new int[other.Size()]), - end_(std::copy(other.begin_, other.end_, begin_)), - capacity_(other.end_) {} + SimpleVector(const SimpleVector& other) { + if (other.Empty()) { + begin_ = end_ = capacity_ = nullptr; + return; + } + + size_t capacity = other.Capacity(); + begin_ = new int[capacity]; + end_ = std::copy(other.begin_, other.end_, begin_); + capacity_ = begin_ + capacity; + } - SimpleVector(SimpleVector&& other) : begin_(other.begin_), end_(other.end_), capacity_(other.capacity_) { + SimpleVector(SimpleVector&& other) : end_(other.end_), capacity_(other.capacity_) { + if (begin_) { + delete[] begin_; + } + + begin_ = other.begin_; other.begin_ = nullptr; other.end_ = nullptr; other.capacity_ = nullptr; @@ -28,13 +46,35 @@ class SimpleVector { } SimpleVector& operator=(const SimpleVector& other) { - begin_ = new int[other.Size()]; + if (&other == this) { + return *this; + } + + if (begin_) { + delete[] begin_; + } + + if (other.Empty()) { + begin_ = end_ = capacity_ = nullptr; + return *this; + } + + size_t capacity = other.Capacity(); + begin_ = new int[capacity]; end_ = std::copy(other.begin_, other.end_, begin_); - capacity_ = end_; + capacity_ = begin_ + capacity; return *this; } SimpleVector& operator=(SimpleVector&& other) { + if (&other == this) { + return *this; + } + + if (begin_) { + delete[] begin_; + } + begin_ = other.begin_; end_ = other.end_; capacity_ = other.capacity_; @@ -44,7 +84,11 @@ class SimpleVector { return *this; } - int& operator[](size_t idx){ + int& operator[](size_t idx) { + return begin_[idx]; + } + + const int& operator[](size_t idx) const { return begin_[idx]; } @@ -53,13 +97,194 @@ class SimpleVector { size_t Capacity() const noexcept; bool Empty() const noexcept; const int* Data() const; + const int* Begin() const; + const int* End() const; void PushBack(int value); void PopBack(); - - + int* Insert(size_t pos, int value); + int* Insert(const int* elem, int value); + int* Erase(size_t pos); + int* Erase(const int* value); + void Clear(); + void Resize(size_t size, int value); + void Reserve(size_t capacity); private: int* begin_ = nullptr; int* end_ = nullptr; int* capacity_ = nullptr; + + void ChangeCapacity(size_t capacity, int value, bool init_with_value); }; + +// Тут подошл бы обычный InreaseCapacity, который был бы проще, но меня переклинило +// и я вместо ТЗ смотрел на описание реализации std::vector, думая, что нужно делать +// shrink_to_fit +void SimpleVector::ChangeCapacity(size_t capacity, int value = 0, bool init_with_value = false) { + size_t size = std::min(Size(), capacity); + int* newSimpleVector = new int[capacity]; + + if (begin_) { + end_ = std::copy(begin_, begin_ + size, newSimpleVector); + delete[] begin_; + } + + begin_ = newSimpleVector; + end_ = begin_ + size; + capacity_ = begin_ + capacity; + + if (init_with_value && capacity > size) { + std::fill(end_, capacity_, value); + end_ = capacity_; + } +} + +bool operator==(const SimpleVector& lhs, const SimpleVector& rhs) { + if (lhs.Size() != rhs.Size()) { + return false; + } + + return std::equal(lhs.Begin(), lhs.End(), rhs.Begin()); +} + +bool operator!=(const SimpleVector& lhs, const SimpleVector& rhs) { + return !(lhs == rhs); +} + +void SimpleVector::Swap(SimpleVector& other) { + // Запрета на std::swap нет, используем >:) + std::swap(begin_, other.begin_); + std::swap(end_, other.end_); + std::swap(capacity_, other.capacity_); +} + +size_t SimpleVector::Size() const noexcept { + return end_ - begin_; +} + +size_t SimpleVector::Capacity() const noexcept { + return capacity_ - begin_; +} + +bool SimpleVector::Empty() const noexcept { + return end_ == begin_ ? true : false; +} + +const int* SimpleVector::Data() const { + return begin_; +} + +const int* SimpleVector::Begin() const { + return begin_; +} + +const int* SimpleVector::End() const { + return end_; +} + +void SimpleVector::PushBack(int value) { + if (end_ != capacity_) { + *end_ = value; + ++end_; + return; + } + + if (Empty()) { + ChangeCapacity(1, value, true); + return; + } + + ChangeCapacity(Capacity() * 2); + + *end_ = value; + ++end_; +} + +void SimpleVector::PopBack() { + if (end_ != begin_) { + --end_; + } +} + +int* SimpleVector::Insert(size_t pos, int value) { + if (pos > Size()) { + return end_; + } + + if (begin_ + pos == end_) { + PushBack(value); + return end_; + } + + if (end_ == capacity_) { + ChangeCapacity(Capacity() * 2); + } + + std::copy_backward(begin_ + pos, end_, end_ + 1); + begin_[pos] = value; + ++end_; + return begin_ + pos; +} + +int* SimpleVector::Insert(const int* elem, int value) { + if (!elem) { + return end_; + } + + return Insert(elem - begin_, value); +} + +int* SimpleVector::Erase(size_t pos) { + if (pos >= Size()) { + return end_; + } + + std::copy(begin_ + pos + 1, end_, begin_ + pos); + --end_; + return begin_ + pos; +} + +int* SimpleVector::Erase(const int* elem) { + if (!elem) { + return end_; + } + + return Erase(elem - begin_); +} + +void SimpleVector::Clear() { + end_ = begin_; +} + +void SimpleVector::Resize(size_t size, int value = 0) { + if (size == Size()) { + return; + } + + if (size < Size()) { + end_ = begin_ + size; + return; + } + + ChangeCapacity(size, value, true); +} + +void SimpleVector::Reserve(size_t capacity) { + if (capacity <= Capacity()) { + return; + } + + ChangeCapacity(capacity); +} + +auto begin(const SimpleVector& sVect) { + return sVect.Begin(); +} + +auto end(const SimpleVector& sVect) { + return sVect.End(); +} + +void swap(SimpleVector& sVect1, SimpleVector& sVect2) { + sVect1.Swap(sVect2); +} From 915d830e1af7426cda35840391987bd4286a3c48 Mon Sep 17 00:00:00 2001 From: Radiy Date: Sat, 14 Feb 2026 22:34:04 +0500 Subject: [PATCH 49/49] add (fix): add string_view task --- 05_week/tasks/string_view/string_view.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/05_week/tasks/string_view/string_view.cpp b/05_week/tasks/string_view/string_view.cpp index e8f1fbba..a65effbd 100644 --- a/05_week/tasks/string_view/string_view.cpp +++ b/05_week/tasks/string_view/string_view.cpp @@ -1,9 +1,6 @@ #include #include -#include #include -#include - class StringView { public: @@ -145,6 +142,10 @@ size_t StringView::Find(char symbol, size_t start = 0) const { } size_t StringView::Find(const StringView& str, size_t start = 0) const { + if (str.Empty()) { + return 0; + } + if (start > Size() || str.Size() > Size() || Empty()) { return npos; }