-
Notifications
You must be signed in to change notification settings - Fork 33
Бобровских Сергей #38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
WIP: week_01
WIP: week 02
|
|
||
| double a_ = static_cast<double>(a); | ||
| double b_ = static_cast<double>(b); | ||
| double c_ = static_cast<double>(c); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
это лишнее, вариант выше был лучше, дальше также
| // Один корень линейного уравнения | ||
| PrintRoot(-c_ / b_); | ||
| } | ||
| return; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше не плодить вложенные ветвления, короткие условия как в начале лучше, немного больше может получится проверок на 0, но это не страшно
| return; | ||
| } | ||
|
|
||
| double D = b_*b_ - 4*a_*c_; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
в данном случае лучше здесь сделать static_cast для одного b, а вместо 4 использовать 4.0
| std::cout << "no solutions"; | ||
| } else { | ||
| // Один корень линейного уравнения | ||
| PrintRoot(-c_ / b_); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше static_cast одной переменной, без создания
| PrintRoot(x); | ||
| } | ||
| else { | ||
| std::cout << "no solutions"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше начать с коротких ветвей (D < 0) с return а основной случай D > 0 вынести из под условия, чтобы не было лишней вложенность
|
|
||
| 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) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ptr не удачно название здесь, лучше func_arr например, более соответствует действительности
| /* 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; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
для указателей часто принято не использовать явное сравнение с nullptr, а использовать неявное приведение к bool !begin || !end будет короче
| 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) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- пробел после if и for ставится
| for (size_t i = 0; i < sizeof(int); ++i) { | ||
| std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[i]); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно было попробовать избавиться от дублирование, тело одинаковое
| void PrintMemory(double /* write arguments here */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| void PrintMemory(double value, bool reverseBytes = false) { | ||
| unsigned char* bytes = reinterpret_cast<unsigned char*>(&value); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
это полное дублирование кода, лучше было из данных функций после получения указателя и зная sizeof от типа вызыватьтретью функцию которая как раз выполняет работу
|
|
||
| for (const char* ptr = begin + 1; ptr < end; ++ptr) { | ||
| if (*ptr == *(ptr - 1)) { | ||
| current_count++; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
это должен быть префиксный инкременет
| for (const char* ptr = begin + 1; ptr < end; ++ptr) { | ||
| if (*ptr == *(ptr - 1)) { | ||
| current_count++; | ||
| } else { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше выше написать continue, а тут избавится от вложенности лишнего else
| longest_ptr = current_ptr; | ||
| } | ||
| count = max_count; | ||
| return const_cast<char*>(longest_ptr); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
это UB, так как мы можем принять изначально указатель на константный объект, нужно было написать две функции у одной принимаемые и возвращаемые указатели на константу, а другого простые, и вот уже из функции без константости корректно было бы вызывать константную версию и снимать константность с результата const_cast, так как была бы увереность, что объект изначально не константный
| if(ptr == end) { break; } | ||
| ++count; | ||
| } | ||
| std::cout << "]\n"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В данном случае это тоже практически полное дублирование кода, можно и нужно от него избавиться
| template <typename T> | ||
| void SwapPtr(T*& ptr1, T*& ptr2) { | ||
| // Проверяем, указывают ли ptr1 и ptr2 на указатели | ||
| if constexpr (std::is_pointer_v<std::remove_pointer_t<T>>) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
как будто это уже лишнее, и вывод типов шаблона справился бы без этого
|
|
||
| void SwapPtr(/* write arguments here */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| template <typename T> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно было и без шаблона получить решение
| stats.sd += static_cast<long long>(num) * num; | ||
| } | ||
| // Вычисляем среднее значение | ||
| stats.avg = static_cast<double>(stats.avg) / numbers.size(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
stats.avg уже имеет тип double поэтому каст тут лишний и можно было использовать /=
| } | ||
| else { | ||
| stats.sd = 0; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
как будто это лишнее, либо можно было компактнее переписать
| static const std::map<char, int> priority = { | ||
| {'Z', 0}, {'D', 1}, {'C', 2}, {'B', 3}, {'A', 4} | ||
| }; | ||
| return priority.at(mark); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
это плохой вариант, так как символы оценок уже упорядочены, иможно было использовать напрямую коды символов, данные подход не гибкий, в случае добавления буков например Y или F, любой, придется переписыватть все начения, очень неудобно
| if (lhs.course != rhs.course) { | ||
| return lhs.course > rhs.course; | ||
| } | ||
| return lhs.birth_date < rhs.birth_date; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
это тоже можно сделать компактно с std::tie так как в если менять местами поля для rhs lhs в правом и левом операнде, при одном знаке <, можно некоторые поля сравнивать на <, а некотоыре на >
|
|
||
| for (size_t i = 0; i < vec.size(); ++i) { | ||
| if (predicate(vec[i])) { | ||
| if (i != write_index) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше выше убрать лишнюю вложенность либо инвертировав условие и continue сделать у предиката
| #include <stdexcept> | ||
| #include <vector> | ||
|
|
||
| using IntVecIterator = std::vector<int>::const_iterator; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше отметить что он константный, cit, как вариант можно было сделать два псевдонима, чтобыбыло понятнее какой min какой max, тут понятно по названию функции, но в CitMin CitMax например тоже можно
| } | ||
|
|
||
| if (*local_min < *min_it) min_it = local_min; | ||
| if (*local_max >= *max_it) max_it = local_max; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
как будто можно было сразу стремиться делать только нужную операцию, объединив условия, не используя локальные итераторы, меньше памяти и кода
| struct Coord2D { | ||
| int x; | ||
| int y; | ||
| Coord2D(int x_val = 0, int y_val = 0) : x(x_val), y(y_val) {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше было указать значения по умолчанию у полей и не писатьтривиальный конструктор для структуры, так как компилятор самостоятельно с этим справится
| 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) {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
аналогичная история, конструкторы лишние, если использовать тот же подход
| } | ||
|
|
||
| std::ostream& operator<<(std::ostream& os, const CircleRegionList& circle_vector) { | ||
| os << '{'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше обработать отдельно случай empty короткой ветвью с выходом
и тем самым вынести основной код извложенности в if, когда тело длинное, приходится посмотреть, чем все заканчивается, чтобы понять что в итоге будет выводится, а при коротких ветвях с return все понятно
| sequence.push_back(current); | ||
| current += step; | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
возможно может стоит предпосчитать количество шагов и оставить один цикл, чтобы не дублировать
| } | ||
| std::vector<int> Unique(std::vector<int> sorted_nums) { | ||
| std::vector<int> unique_nums; | ||
| if(sorted_nums.empty()) {return unique_nums;} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
что- то тут стилькода поменялся
| int previous = *(sorted_nums.begin()); | ||
| unique_nums.push_back(previous); | ||
| for(auto num : sorted_nums) { | ||
| if(previous != num) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше убрать вложенность previous == num - > continue
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@WhoAmI1909 отметил следующие моменты
- дублирование кода
- UB const_cast
- местами лишние переменные
- не все задачи решены
No description provided.