diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..05ffd7d1 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"}; + return static_cast(a) + static_cast(b); } \ No newline at end of file diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index 75e7c652..340c1c97 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -1,5 +1,6 @@ #include #include +#include enum class CheckFlags : uint8_t { @@ -14,5 +15,40 @@ enum class CheckFlags : uint8_t { }; void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; + // Значение находится в допустимом диапазоне + uint8_t value = static_cast(flags); + if (value == 0) { + std::cout << "[]"; + return; + } + if (value > static_cast(CheckFlags::ALL)) { + return; + } + // Последнее значение + if (value == static_cast(CheckFlags::ALL)) { + std::cout << "[TIME,DATE,USER,CERT,KEYS,DEST]"; + return; + } + + std::cout << "["; + bool first = true; + + const std::pair flag_names[] = { + {CheckFlags::TIME, "TIME"}, + {CheckFlags::DATE, "DATE"}, + {CheckFlags::USER, "USER"}, + {CheckFlags::CERT, "CERT"}, + {CheckFlags::KEYS, "KEYS"}, + {CheckFlags::DEST, "DEST"} + }; + + for (const auto& [flag, name] : flag_names) { + if (value & static_cast(flag)) { + if (!first) std::cout << ","; + std::cout << name; + first = false; + } + } + + std::cout << "]"; } diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..c9e08123 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,55 @@ +double FT_IN_M = 1.0 / 0.3048; +double FT_IN_INCHES = 12.0; +double INCH_IN_CM = 2.54; + +// Футы в другие величины +double operator""_ft_to_m(long double ft) { + return ft / FT_IN_M; +} + +double operator""_ft_to_cm(long double ft) { + return ft / FT_IN_M * 100.0; +} + +double operator""_ft_to_in(long double ft) { + return ft * FT_IN_INCHES; +} + +// Дюймы в другие величины +double operator""_in_to_ft(long double in) { + return in / FT_IN_INCHES; +} + +double operator""_in_to_cm(long double in) { + return in * INCH_IN_CM; +} + +double operator""_in_to_m(long double inches) { + return inches * INCH_IN_CM / 100; +} + +// См в другие величины +double operator""_cm_to_m(long double centimeters) { + return centimeters / 100; +} + +double operator""_cm_to_in(long double centimeters) { + return centimeters / INCH_IN_CM; +} + +double operator""_cm_to_ft(long double centimeters) { + return centimeters / (FT_IN_INCHES * INCH_IN_CM); +} + +// Метры в другие величины +double operator""_m_to_ft(long double meters) { + return meters * 100 / (INCH_IN_CM * FT_IN_INCHES); +} + +double operator""_m_to_in(long double meters) { + return meters * 100 / INCH_IN_CM; +} + +double operator""_m_to_cm(long double meters) { + return meters * 100; +} \ No newline at end of file diff --git a/01_week/tasks/print_bits/print_bits.cpp b/01_week/tasks/print_bits/print_bits.cpp index a48a43c1..8dbbc6fa 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -1,7 +1,27 @@ #include #include +#include void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; + using std::cout; + // Проверка корректности размера + if (bytes == 0 || bytes > 8) { + return; + } + std::cout << "0b"; + + // Проходим по всем битам, начиная со старшего + for (size_t pos = bytes * 8; pos > 0; --pos) { + // Получаем значение бита на текущей позиции + int bit = (value >> (pos - 1)) & 1; + std::cout << bit; + + // Добавляем апостроф между байтами (после каждых 4 бит, кроме последней группы) + if ((pos - 1) > 0 && (pos - 1) % 4 == 0) { + std::cout << "'"; + } + } + + std::cout << "\n"; } diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..6e3c300c 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,56 @@ #include +#include +#include +#include +void PrintRoot(double x) { + // Для избавления от заведомо небольших значений + if (std::abs(x) < 1e-10) { + x = 0.0; + } + std::cout << std::setprecision(6) << x; +} void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; + if(a == 0 && b == 0 && c == 0) { + std::cout << "infinite solutions"; + return; + } + + double a_ = static_cast(a); + double b_ = static_cast(b); + double c_ = static_cast(c); + + if(a_ == 0) { + if(b_ == 0) { + // Нет решений + std::cout << "no solutions"; + } else { + // Один корень линейного уравнения + PrintRoot(-c_ / b_); + } + return; + } + + double D = b_*b_ - 4*a_*c_; + if (D > 0) { + double sqrt_d = std::sqrt(D); + double x1 = (-b_ - sqrt_d) / (2.0 * a_); + double x2 = (-b_ + sqrt_d) / (2.0 * a_); + + // Гарантируем, что x1 < x2 + if (x1 > x2) { + std::swap(x1, x2); + } + PrintRoot(x1); + std::cout << " "; + PrintRoot(x2); + } + else if (D == 0) { + double x = -b_ / (2.0 * a_); + PrintRoot(x); + } + else { + std::cout << "no solutions"; + } } \ No newline at end of file diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..06782da0 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,7 +1,15 @@ -#include +#include #include +#include double CalculateRMS(double values[], size_t size) { - throw std::runtime_error{"Not implemented"}; + if(size == 0 || values == nullptr) { // Проверка на отсутствие элементов в массиве и на нулевой указатель + return 0.0; + } + double square_sum = 0.0; + for(size_t i = 0; i < size; ++i) { + square_sum += values[i] * values[i]; + } + return sqrt(square_sum/size); } \ No newline at end of file diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index b327e68d..aa461fe8 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,16 @@ -#include -double ApplyOperations(double a, double b /* other arguments */) { - throw std::runtime_error{"Not implemented"}; +double ApplyOperations(double a, double b, double (*ptr[])(double, double), size_t size) { + double sum = 0.0; + + if(size == 0 || ptr == nullptr) { + return sum; + } + + for (size_t i = 0; i < size; ++i) { + if(ptr[i] == nullptr) continue; + sum += ptr[i](a, b); + } + + return sum; } \ No newline at end of file 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..c4290840 100644 --- a/02_week/tasks/last_of_us/last_of_us.cpp +++ b/02_week/tasks/last_of_us/last_of_us.cpp @@ -1,6 +1,11 @@ #include -/* return_type */ FindLastElement(/* ptr_type */ begin, /* ptr_type */ end, /* func_type */ predicate) { - throw std::runtime_error{"Not implemented"}; +const int* FindLastElement(const int* begin, const int* end, bool (*predicate)(const int)) { + if((begin > end) || (begin == nullptr) || (end == nullptr)) return end; + + for(const int* ptr = end - 1; ptr >= begin; --ptr) { + if (predicate(*ptr)) {return ptr;} + } + return end; } \ No newline at end of file diff --git a/02_week/tasks/little_big/little_big.cpp b/02_week/tasks/little_big/little_big.cpp index abe24379..799259df 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,45 @@ #include +#include +#include +#include -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(int value, bool reverse = false) { + unsigned char* bytes = reinterpret_cast(&value); + + std::cout << "0x"; + + if (reverse) { + // Вывод в обратном порядке (big-endian) + for (int i = sizeof(int) - 1; i >= 0; --i) { + std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(bytes[i]); + } + } else { + // Вывод в естественном порядке (little-endian) + for (size_t i = 0; i < sizeof(int); ++i) { + std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(bytes[i]); + } + } + + std::cout << std::endl; } -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(double value, bool reverseBytes = false) { + unsigned char* bytes = reinterpret_cast(&value); + + std::cout << "0x"; + + if (reverseBytes) { + // Вывод в обратном порядке (big-endian) + for (int i = sizeof(double) - 1; i >= 0; --i) { + std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(bytes[i]); + } + } else { + // Вывод в естественном порядке (little-endian) + for (size_t i = 0; i < sizeof(double); ++i) { + std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(bytes[i]); + } + } + + std::cout << std::endl; } \ No newline at end of file diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..cdb03438 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,34 @@ #include -/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) { - throw std::runtime_error{"Not implemented"}; +char* FindLongestSubsequence(const char* begin, const char* end, size_t& count) { + if (begin == nullptr || end == nullptr || begin >= end) { + count = 0; + return nullptr; + } + + const char* longest_ptr = begin; + const char* current_ptr = begin; + size_t max_count = 1; + size_t current_count = 1; + + for (const char* ptr = begin + 1; ptr < end; ++ptr) { + if (*ptr == *(ptr - 1)) { + current_count++; + } else { + if(current_count > max_count) { + max_count = current_count; + longest_ptr = current_ptr; + } + current_ptr = ptr; + current_count = 1; + } + } + + if(current_count > max_count) { + max_count = current_count; + longest_ptr = current_ptr; + } + count = max_count; + return const_cast(longest_ptr); } diff --git a/02_week/tasks/pretty_array/pretty_array.cpp b/02_week/tasks/pretty_array/pretty_array.cpp index 48eab341..30509eb0 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,38 @@ #include +#include - -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintArray(const int* begin, const int* end, int constraint = 0) { + if (begin == end || begin == nullptr || end == nullptr) + { + std::cout << "[]\n"; + return; + } + + int count = 0; + std::cout << "["; + if(begin < end) { + for(const int* ptr = begin; ptr < end; ++ptr) { + if((count == constraint) && (constraint != 0)) { + count = 0; + std::cout << "...\n "; + } + std::cout << *ptr; + if(ptr != end - 1) { std::cout << ", "; } + ++count; + } + std::cout << "]\n"; + } else { + ++end; + for(const int* ptr = begin; ptr >= end; --ptr) { + if((count == constraint) && (constraint != 0)) { + count = 0; + std::cout << "...\n "; + } + std::cout << *ptr; + if(ptr != end) { std::cout << ", "; } + if(ptr == end) { break; } + ++count; + } + std::cout << "]\n"; + } } \ No newline at end of file diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index 93db625d..ab74aef4 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,17 @@ #include -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +template +void SwapPtr(T*& ptr1, T*& ptr2) { + // Проверяем, указывают ли ptr1 и ptr2 на указатели + if constexpr (std::is_pointer_v>) { + // T* - это указатель на указатель (например: int**) + // Меняем значения, на которые указываем + SwapPtr(*ptr1, *ptr2); // Рекурсивный вызов + } + + // Меняем сами указатели + T* temp = ptr1; + ptr1 = ptr2; + ptr2 = temp; } \ No newline at end of file diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index b941c211..49bbdd56 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -1,11 +1,31 @@ #include - +#include +#include struct DataStats { double avg = 0.0; double sd = 0.0; }; -/* return_type */ CalculateDataStats(/* args */) { - throw std::runtime_error{"Not implemented"}; +DataStats CalculateDataStats(std::vector numbers) { + DataStats stats; + + if(numbers.empty()) { + return stats; + } + + for(auto num : numbers) { + stats.avg += num; + stats.sd += static_cast(num) * num; + } + // Вычисляем среднее значение + stats.avg = static_cast(stats.avg) / numbers.size(); + + if (numbers.size() > 1) { + stats.sd = std::sqrt((stats.sd - numbers.size() * stats.avg * stats.avg) / numbers.size()); + } + else { + stats.sd = 0; + } + return stats; } diff --git a/03_week/tasks/easy_compare/easy_compare.cpp b/03_week/tasks/easy_compare/easy_compare.cpp index dd5cb7f6..8145b476 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -1,10 +1,17 @@ #include +#include +int markPriority(char mark) { + static const std::map priority = { + {'Z', 0}, {'D', 1}, {'C', 2}, {'B', 3}, {'A', 4} + }; + return priority.at(mark); +} struct Date { - unsigned year; - unsigned month; - unsigned day; + unsigned year = 0u; + unsigned month = 0u; + unsigned day = 0u; }; struct StudentInfo { @@ -13,4 +20,43 @@ struct StudentInfo { int score; unsigned course; Date birth_date; -}; \ No newline at end of file +}; + +bool operator==(const Date& lhs, const Date& rhs) { + return std::tie(lhs.year, lhs.month, lhs.day) == + std::tie(rhs.year, rhs.month, rhs.day); +} + +bool operator<(const Date& lhs, const Date& rhs) { + return std::tie(lhs.year, lhs.month, lhs.day) < + std::tie(rhs.year, rhs.month, rhs.day); +} + +bool operator<=(const Date& lhs, const Date& rhs) { + return lhs < rhs || lhs == rhs; +} + +bool operator>(const Date& lhs, const Date& rhs) { + return !(lhs <= rhs); +} + +bool operator>=(const Date& lhs, const Date& rhs) { + return !(lhs < rhs); +} + +bool operator==(const StudentInfo& lhs, const StudentInfo& rhs) { + return lhs.mark == rhs.mark && lhs.score == rhs.score; +} + +bool operator<(const StudentInfo& lhs, const StudentInfo& rhs) { + if (markPriority(lhs.mark) != markPriority(rhs.mark)) { + return markPriority(lhs.mark) < markPriority(rhs.mark); + } + if (lhs.score != rhs.score) { + return lhs.score < rhs.score; + } + if (lhs.course != rhs.course) { + return lhs.course > rhs.course; + } + return lhs.birth_date < rhs.birth_date; +} diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index 6648cb39..06fe0a15 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -1,6 +1,21 @@ #include +#include -/* return_type */ Filter(/* args */) { - throw std::runtime_error{"Not implemented"}; +void Filter(std::vector& vec, bool (*predicate)(int)) { + size_t write_index = 0; + + if (vec.empty() || predicate == nullptr) { + return; + } + + for (size_t i = 0; i < vec.size(); ++i) { + if (predicate(vec[i])) { + if (i != write_index) { + vec[write_index] = vec[i]; + } + ++write_index; + } + } + vec.resize(write_index); } \ No newline at end of file diff --git a/03_week/tasks/find_all/find_all.cpp b/03_week/tasks/find_all/find_all.cpp index 74f393b2..d2951d54 100644 --- a/03_week/tasks/find_all/find_all.cpp +++ b/03_week/tasks/find_all/find_all.cpp @@ -1,6 +1,18 @@ #include +#include - -/* return_type */ FindAll(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::vector FindAll(const std::vector& container, bool (*predicate)(int)) { + if(container.empty() || predicate == nullptr) { + return {}; + } + + std::vector result; + + for (size_t i = 0; i < container.size(); ++i) { + if (predicate(container[i])) { + result.push_back(i); + } + } + result.shrink_to_fit(); + return result; } \ No newline at end of file diff --git a/03_week/tasks/minmax/minmax.cpp b/03_week/tasks/minmax/minmax.cpp index c2869799..68c8e928 100644 --- a/03_week/tasks/minmax/minmax.cpp +++ b/03_week/tasks/minmax/minmax.cpp @@ -1,6 +1,45 @@ #include +#include +using IntVecIterator = std::vector::const_iterator; -/* return_type */ MinMax(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::pair MinMax(const std::vector& numbers) { + if (numbers.empty()) { + return {numbers.end(), numbers.end()}; + } + + IntVecIterator min_it = numbers.begin(); + IntVecIterator max_it = numbers.begin(); + + auto it = numbers.begin() + 1; + const auto last = numbers.end(); + + while (it + 1 < last) { + IntVecIterator a = it; + IntVecIterator b = it + 1; + + IntVecIterator local_min, local_max; + if (*a <= *b) { + local_min = a; + local_max = b; + } else { + local_min = b; + local_max = a; + } + + if (*local_min < *min_it) min_it = local_min; + if (*local_max >= *max_it) max_it = local_max; + + it += 2; + } + + if (it != last) { + if (*it < *min_it) { + min_it = it; + } else if (*it >= *max_it) { + max_it = it; + } + } + + return {min_it, max_it}; } diff --git a/03_week/tasks/os_overload/os_overload.cpp b/03_week/tasks/os_overload/os_overload.cpp index e473418d..ba566298 100644 --- a/03_week/tasks/os_overload/os_overload.cpp +++ b/03_week/tasks/os_overload/os_overload.cpp @@ -1,21 +1,60 @@ #include #include #include +#include struct Coord2D { int x; int y; + Coord2D(int x_val = 0, int y_val = 0) : x(x_val), y(y_val) {} }; struct Circle { Coord2D coord; - unsigned radius; + unsigned radius = 1; + Circle() : coord(), radius(1) {} // Default + explicit Circle(Coord2D c, unsigned r = 1) : coord(c), radius(r) {} + Circle(unsigned r) : coord(), radius(r) {} }; using CircleRegion = std::pair; using CircleRegionList = std::vector; -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Оператор вывода для Coord2D +std::ostream& operator<<(std::ostream& os, const Coord2D& coord) { + os << '(' << coord.x << ", " << coord.y << ')'; + return os; +} + +// Оператор вывода для Circle +std::ostream& operator<<(std::ostream& os, const Circle& circle) { + os << "circle["; + if (circle.radius > 0) { + os << circle.coord << ", r = " << circle.radius; + } + os << ']'; + return os; +} + +// Оператор вывода для CircleRegion +std::ostream& operator<<(std::ostream& os, const CircleRegion& region) { + os << (region.second ? '+' : '-') << region.first; + return os; +} + +std::ostream& operator<<(std::ostream& os, const CircleRegionList& circle_vector) { + os << '{'; + if (!circle_vector.empty()) { + os << '\n'; + for (auto it = circle_vector.begin(); it != circle_vector.end(); ++it) { + os << '\t' << *it; + if (std::next(it) != circle_vector.end()) { + os << ','; + } + os << '\n'; + } + } + os << '}'; + return os; } diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index d2085495..a9f67dc8 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -2,6 +2,29 @@ #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) { + int size = 0; + if(from == to || (from > to && step > 0) || (from < to && step < 0) || step == 0) { + return {}; + } + if ((step > 0 && from < to) || (step < 0 && from > to)) { + size = (std::abs(to - from) + std::abs(step) - 1) / std::abs(step); + } + std::vector sequence; + sequence.reserve(size); + + int current = from; + if (step > 0) { + while (current < to) { + sequence.push_back(current); + current += step; + } + } else { + while (current > to) { + sequence.push_back(current); + current += step; + } + } + + return sequence; } diff --git a/03_week/tasks/unique/unique.cpp b/03_week/tasks/unique/unique.cpp index 9d2545bb..9161363c 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -1,6 +1,17 @@ #include #include -/* return_type */ Unique(/* args */) { - throw std::runtime_error{"Not implemented"}; -} +std::vector Unique(std::vector sorted_nums) { + std::vector unique_nums; + if(sorted_nums.empty()) {return unique_nums;} + int previous = *(sorted_nums.begin()); + unique_nums.push_back(previous); + for(auto num : sorted_nums) { + if(previous != num) { + previous = num; + unique_nums.push_back(previous); + } + } + unique_nums.shrink_to_fit(); + return unique_nums; +} \ No newline at end of file diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 2a9f8493..526c2b23 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,6 +1,151 @@ #include - +#include +#include +#include +#include class Queue { +private: + mutable std::vector input_stack; + mutable std::vector output_stack; + + void MoveInputToOutput() const; +public: + Queue(); + Queue(std::stack stack); + Queue(const std::vector& vec); + Queue(std::initializer_list init_list); + explicit Queue(size_t size); + + void Push(int value); + bool Pop(); + int& Front(); + const int& Front() const; + int& Back(); + const int& Back() const; + bool Empty() const; + size_t Size() const; + void Clear(); + void Swap(Queue& other); + + bool operator==(const Queue& other) const; + bool operator!=(const Queue& other) const; }; + +void Queue::MoveInputToOutput() const { + while (!input_stack.empty()) { + output_stack.push_back(input_stack.back()); + input_stack.pop_back(); + } + } + +Queue::Queue() = default; + +Queue::Queue(std::stack stack) { + while (!stack.empty()) { + input_stack.push_back(stack.top()); + stack.pop(); + } + std::reverse(input_stack.begin(), input_stack.end()); +} + +Queue::Queue(const std::vector& vec) : input_stack(vec) {} + +Queue::Queue(std::initializer_list init_list) : input_stack(init_list) {} + +Queue::Queue(size_t size) { + input_stack.reserve(size); + output_stack.reserve(size); +} + +void Queue::Push(int value) { + input_stack.push_back(value); +} + +bool Queue::Pop() { + if (Empty()) { + return false; + } + + if (output_stack.empty()) { + MoveInputToOutput(); + } + + output_stack.pop_back(); + return true; +} + +int& Queue::Front() { + if (output_stack.empty()) { + MoveInputToOutput(); + } + + return output_stack.back(); +} + +const int& Queue::Front() const { + if (output_stack.empty()) { + Queue* mutable_this = const_cast(this); + mutable_this->MoveInputToOutput(); + } + + return output_stack.back(); +} + +int& Queue::Back() { + if (!input_stack.empty()) { + return input_stack.back(); + } + + return output_stack.front(); +} + +const int& Queue::Back() const { + if (!input_stack.empty()) { + return input_stack.back(); + } + + return output_stack.front(); +} + +bool Queue::Empty() const { + return input_stack.empty() && output_stack.empty(); +} + +size_t Queue::Size() const { + return input_stack.size() + output_stack.size(); +} + +void Queue::Clear() { + input_stack.clear(); + output_stack.clear(); +} + +void Queue::Swap(Queue& other) { + input_stack.swap(other.input_stack); + output_stack.swap(other.output_stack); +} + +bool Queue::operator==(const Queue& other) const { + if (Size() != other.Size()) { + return false; + } + + Queue q1 = *this; + Queue q2 = other; + + while (!q1.Empty()) { + if (q1.Front() != q2.Front()) { + return false; + } + q1.Pop(); + q2.Pop(); + } + + return true; +} + +bool Queue::operator!=(const Queue& other) const { + return !(*this == other); +} \ No newline at end of file diff --git a/04_week/tasks/queue/test.cpp b/04_week/tasks/queue/test.cpp index 3bc5e562..e49f61e5 100644 --- a/04_week/tasks/queue/test.cpp +++ b/04_week/tasks/queue/test.cpp @@ -443,4 +443,4 @@ TEST_F(QueuePerformanceTest, CapacityCtorCompareWithVector) { std::cout << " Push: " << vector_push_time << " ms" << std::endl; EXPECT_LT(queue_push_time * 1.0, vector_push_time * 1.5); -} \ No newline at end of file +} diff --git a/04_week/tasks/stack/stack.cpp b/04_week/tasks/stack/stack.cpp index 222e4ffc..7e1ee2fe 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -2,5 +2,63 @@ class Stack { + std::vector storage; +public: + Stack() = default; + ~Stack() = default; + void Push(int); + bool Pop(); + int& Top(); + const int& Top() const; + bool Empty() const; + size_t Size() const; + void Clear(); + void Swap(Stack&); + friend bool operator==(const Stack& lhs, const Stack& rhs); + friend bool operator!=(const Stack&, const Stack&); }; + +void Stack::Push(int a) { + storage.push_back(a); +} + +bool Stack::Pop() { + if(storage.empty()) { + return false; + } + storage.pop_back(); + return true; +} + +int& Stack::Top() { + return storage.back(); +} + +const int& Stack::Top() const { + return storage.back(); +} + +bool Stack::Empty() const { + return storage.empty(); +} + +size_t Stack::Size() const { + return storage.size(); +} + +void Stack::Clear() { + storage.clear(); +} + +void Stack::Swap(Stack& other) { + storage.swap(other.storage); +} + +bool operator==(const Stack& lhs, const Stack& rhs) { + return lhs.storage == rhs.storage; +} + +bool operator!=(const Stack& lhs, const Stack& rhs) { + return lhs.storage != rhs.storage; +} diff --git a/05_week/tasks/simple_vector/simple_vector.cpp b/05_week/tasks/simple_vector/simple_vector.cpp index 9b2ea971..335bfcf7 100644 --- a/05_week/tasks/simple_vector/simple_vector.cpp +++ b/05_week/tasks/simple_vector/simple_vector.cpp @@ -1,5 +1,256 @@ - +#include +#include +#include class SimpleVector { +public: + SimpleVector(); + explicit SimpleVector(size_t size); + explicit SimpleVector(size_t size, int value); + SimpleVector(std::initializer_list init); + SimpleVector(const SimpleVector& other); + SimpleVector(SimpleVector&& other) noexcept; + + SimpleVector& operator=(const SimpleVector& other); + SimpleVector& operator=(SimpleVector&& other) noexcept; + + ~SimpleVector(); + + void Swap(SimpleVector& other) noexcept; + + int& operator[](size_t index); + const int& operator[](size_t index) const; + + size_t Size() const; + size_t Capacity() const; + bool Empty() const; + const int* Data() const; + + void PushBack(int value); + void PopBack(); + + int* Insert(const int* pos, int value); + int* Erase(const int* pos); + + void Clear(); + void Resize(size_t new_size, int value = 0); + void Reserve(size_t new_capacity); + + int* begin(); + int* end(); + const int* begin() const; + const int* end() const; + +private: + int* data_; + size_t size_; + size_t capacity_; +}; + +SimpleVector::SimpleVector() + : data_(nullptr), size_(0), capacity_(0) {} + +SimpleVector::SimpleVector(size_t size) + : data_(new int[size]()), size_(size), capacity_(size) {} + +SimpleVector::SimpleVector(size_t size, int value) + : data_(new int[size]), + size_(size), + capacity_(size) +{ + for (size_t i = 0; i < size_; ++i) { + data_[i] = value; + } +} + +SimpleVector::SimpleVector(std::initializer_list init) + : data_(new int[init.size()]), size_(init.size()), capacity_(init.size()) { + std::copy(init.begin(), init.end(), data_); +} + +SimpleVector::SimpleVector(const SimpleVector& other) + : data_(new int[other.capacity_]), + size_(other.size_), + capacity_(other.capacity_) { + std::copy(other.data_, other.data_ + size_, data_); +} + +SimpleVector::SimpleVector(SimpleVector&& other) noexcept + : data_(other.data_), size_(other.size_), capacity_(other.capacity_) { + other.data_ = nullptr; + other.size_ = 0; + other.capacity_ = 0; +} + +SimpleVector& SimpleVector::operator=(const SimpleVector& other) { + if (this != &other) { + SimpleVector tmp(other); + Swap(tmp); + } + return *this; +} + +SimpleVector& SimpleVector::operator=(SimpleVector&& other) noexcept { + if (this != &other) { + delete[] data_; + data_ = other.data_; + size_ = other.size_; + capacity_ = other.capacity_; + other.data_ = nullptr; + other.size_ = 0; + other.capacity_ = 0; + } + return *this; +} + +SimpleVector::~SimpleVector() { + delete[] data_; +} + +void SimpleVector::Swap(SimpleVector& other) noexcept { + std::swap(data_, other.data_); + std::swap(size_, other.size_); + std::swap(capacity_, other.capacity_); +} + +int& SimpleVector::operator[](size_t index) { + return data_[index]; +} + +const int& SimpleVector::operator[](size_t index) const { + return data_[index]; +} + +size_t SimpleVector::Size() const { + return size_; +} + +size_t SimpleVector::Capacity() const { + return capacity_; +} + +bool SimpleVector::Empty() const { + return size_ == 0; +} + +const int* SimpleVector::Data() const { + return data_; +} + +void SimpleVector::Reserve(size_t new_capacity) { + if (new_capacity <= capacity_) return; + + int* new_data = new int[new_capacity]; + std::copy(data_, data_ + size_, new_data); + + delete[] data_; + data_ = new_data; + capacity_ = new_capacity; +} + +void SimpleVector::PushBack(int value) { + if (size_ == capacity_) { + size_t new_capacity = (capacity_ == 0) ? 1 : capacity_ * 2; + Reserve(new_capacity); + } + data_[size_++] = value; +} + +void SimpleVector::PopBack() { + if (size_ > 0) { + --size_; + } +} + +int* SimpleVector::Insert(const int* pos, int value) { + if (pos < data_ || pos > data_ + size_) { + return data_ + size_; + } + + size_t index = pos - data_; + + if (size_ == capacity_) { + size_t new_capacity = (capacity_ == 0) ? 1 : capacity_ * 2; + Reserve(new_capacity); + } + + for (size_t i = size_; i > index; --i) { + data_[i] = data_[i - 1]; + } + + data_[index] = value; + ++size_; + return data_ + index; +} + +int* SimpleVector::Erase(const int* pos) { + if (pos < data_ || pos >= data_ + size_) + return data_ + size_; + + size_t index = pos - data_; + + for (size_t i = index; i + 1 < size_; ++i) { + data_[i] = data_[i + 1]; + } + + --size_; + + return data_ + index; +} + +void SimpleVector::Clear() { + size_ = 0; +} + +void SimpleVector::Resize(size_t new_size, int value) { + if (new_size <= size_) { + size_ = new_size; + return; + } + + if (new_size > capacity_) { + Reserve(new_size); + } + + for (size_t i = size_; i < new_size; ++i) { + data_[i] = value; + } + + size_ = new_size; +} + +int* SimpleVector::begin() { + return data_; +} + +int* SimpleVector::end() { + return data_ + size_; +} + +const int* SimpleVector::begin() const { + return data_; +} + +const int* SimpleVector::end() const { + return data_ + size_; +} + +inline void swap(SimpleVector& lhs, SimpleVector& rhs) noexcept { + lhs.Swap(rhs); +} + +bool operator==(const SimpleVector& lhs, const SimpleVector& rhs) { + if (lhs.Size() != rhs.Size()) + return false; + + for (size_t i = 0; i < lhs.Size(); ++i) { + if (lhs[i] != rhs[i]) + return false; + } + + return true; +} -}; \ No newline at end of file +bool operator!=(const SimpleVector& lhs, const SimpleVector& rhs) { + return !(lhs == rhs); +} \ No newline at end of file diff --git a/05_week/tasks/string_view/string_view.cpp b/05_week/tasks/string_view/string_view.cpp index 438c4536..23e10e3b 100644 --- a/05_week/tasks/string_view/string_view.cpp +++ b/05_week/tasks/string_view/string_view.cpp @@ -3,5 +3,154 @@ class StringView { + size_t size_; + const char* data_; +public: + static const size_t npos = static_cast(-1); + // Constructors + StringView(); // Конструктор по умолчанию + StringView(const std::string&, size_t = 0, size_t = npos); // Конструктор от string, позиции начала подстроки (0), длины подстроки (npos) + StringView(const char*); // Конструктор от С-строки + StringView(const char*, size_t); // Конструктор от С-строки и длины + // Methods + const char* Data() const; + const char& Front() const; + const char& Back() const; + size_t Size() const; + size_t Length() const; + bool Empty() const; + void RemovePrefix(size_t) noexcept; + void RemoveSuffix(size_t) noexcept; + StringView Substr(size_t, size_t = npos) const; + size_t Find(char, size_t = 0) const noexcept; + size_t Find(const StringView&, size_t = 0) const noexcept; + std::string ToString() const; + // Operators + const char& operator[](size_t) const noexcept; +}; -}; \ No newline at end of file +const size_t StringView::npos; + +StringView::StringView(): size_(0), data_(nullptr) {} + +StringView::StringView(const std::string& str, size_t pos, size_t len) { + if (pos > str.size()) { + data_ = nullptr; + size_ = 0; + return; + } + + size_ = std::min(len, str.size() - pos); + data_ = str.data() + pos; +} + +StringView::StringView(const char* cstr) { + if (cstr == nullptr) { + data_ = nullptr; + size_ = 0; + } else { + data_ = cstr; + size_ = std::strlen(cstr); + } +} + +StringView::StringView(const char* cstr, size_t len) { + if (cstr == nullptr) { + data_ = nullptr; + size_ = 0; + } else { + size_ = std::min(len, std::strlen(cstr)); + data_ = cstr; + } +} + +// Methods +const char* StringView::Data() const { + return data_; +} + +const char& StringView::Front() const { + return data_[0]; +} + +const char& StringView::Back() const { + return data_[size_ - 1]; +} + +size_t StringView::Size() const { + return size_; +} + +size_t StringView::Length() const { + return size_; +} + +bool StringView::Empty() const { + return size_ == 0; +} + +void StringView::RemovePrefix(size_t n) noexcept { + if (n >= size_) { + data_ = nullptr; + size_ = 0; + } else { + data_ += n; + size_ -= n; + } +} + +void StringView::RemoveSuffix(size_t n) noexcept { + if (n >= size_) { + size_ = 0; + data_ = nullptr; + } else { + size_ -= n; + } +} + + +std::string StringView::ToString() const { + return std::string(data_, size_); +} + +StringView StringView::Substr(size_t pos, size_t len) const { + if (pos > size_) { + return StringView(); + } + return StringView(data_ + pos, std::min(len, size_ - pos)); +} + +const char& StringView::operator[](size_t index) const noexcept { + return data_[index]; +} + +size_t StringView::Find(char ch, size_t pos) const noexcept { + if (pos >= size_) { + return npos; + } + + for (size_t i = pos; i < size_; ++i) { + if (data_[i] == ch) { + return i; + } + } + return npos; +} + +size_t StringView::Find(const StringView& sv, size_t pos) const noexcept { + if (sv.size_ == 0) { + return pos <= size_ ? pos : npos; + } + + if (sv.size_ > size_ || pos >= size_) { + return npos; + } + + for (size_t i = pos; i + sv.size_ <= size_; ++i) { + if (std::memcmp(data_ + i, sv.data_, sv.size_) == 0) { + return i; + } + } + + return npos; +} \ No newline at end of file diff --git a/05_week/tasks/tracer/tracer.cpp b/05_week/tasks/tracer/tracer.cpp index 2ccfb417..00fcc49f 100644 --- a/05_week/tasks/tracer/tracer.cpp +++ b/05_week/tasks/tracer/tracer.cpp @@ -2,5 +2,127 @@ class Tracer { + int id; // unique identifier of the object + std::string name; // name of the object -}; \ No newline at end of file +public: + static size_t count; // number of created objects + static size_t default_ctor; // number of calls to default constructor + static size_t str_ctor; // number of calls to constructor with string argument + static size_t copy_ctor; // number of calls to copy constructor + static size_t move_ctor; // number of calls to move constructor + static size_t copy_assign; // number of calls to copy assignment operator + static size_t move_assign; // number of calls to move assignment operator + static size_t dtor; // number of calls to destructor + static size_t alive; // number of currently alive objects + + void static ResetStats(); // resets all static counters to zero + Tracer(); // Default constructor + Tracer(const std::string&); // Constructor with string argument + Tracer(const Tracer&); // Copy constructor + Tracer(Tracer&&) noexcept; // Move constructor + Tracer& operator=(const Tracer&); + Tracer& operator=(Tracer&&) noexcept; + ~Tracer(); // Destructor + // Methods + int Id() const noexcept; // returns the id of the object + const std::string& Name() const noexcept; // returns the linked name of the object + const char* Data() const noexcept; // returns the linked name of the object +}; + +// Static member initialization +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; + +// Reset counters +void Tracer::ResetStats() { + default_ctor = 0; + str_ctor = 0; + copy_ctor = 0; + move_ctor = 0; + copy_assign = 0; + move_assign = 0; + dtor = 0; + alive = 0; + count = 0; +} + +// Default constructor +Tracer::Tracer() + : id(++count), + name("obj_" + std::to_string(id)) +{ + ++default_ctor; + ++alive; +} + +// Constructor with string argument +Tracer::Tracer(const std::string& name) + : id(++count), + name(name + "_" + std::to_string(id)) +{ + ++str_ctor; + ++alive; +} + +// Copy constructor +Tracer::Tracer(const Tracer& other) + : id(++count), + name(other.name) +{ + ++copy_ctor; + ++alive; +} + +// Move constructor +Tracer::Tracer(Tracer&& other) noexcept + : id(++count), + name(std::move(other.name)) +{ + ++move_ctor; + ++alive; +} + +// Copy assignment operator +Tracer& Tracer::operator=(const Tracer& other) { + if(this != &other) { + name = other.name; + copy_assign++; + } + return *this; +} + +// Move assignment operator +Tracer& Tracer::operator=(Tracer&& other) noexcept { + if(this != &other) { + name = std::move(other.name); + move_assign++; + } + return *this; +} + +// Destructor +Tracer::~Tracer() { + ++dtor; + --alive; +} + +// Methods +int Tracer::Id() const noexcept { + return id; +} + +const std::string& Tracer::Name() const noexcept { + return name; +} + +const char* Tracer::Data() const noexcept { + return name.c_str(); +} \ No newline at end of file