-
Notifications
You must be signed in to change notification settings - Fork 33
Михайлов Илья #27
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?
Михайлов Илья #27
Conversation
|
|
||
| int64_t Addition(int a, int b) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| return static_cast<int64_t>(a) + static_cast<int64_t>(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.
Лишний каст, второй операнд не следует приводить явно, так как он бы преобразовался с помощью неявного каста. Принято использовать такую возможность и не писать явный каст самостоятельно второй раз
| } | ||
| size_t CharChanger(char array[], size_t, char delimiter = ' ') { | ||
| int counter = 0; // Счётчик повторяющихся символов | ||
| int write = 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.
В данном случае это позиция, не указатель, лучше не вводить в замешательство, а еще может лучше добавть префикс pos_write, тогда комментарии излишни
| throw std::runtime_error{"Not implemented"}; | ||
| } | ||
| size_t CharChanger(char array[], size_t, char delimiter = ' ') { | ||
| int counter = 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.
Лучше, чтобы название отражало то, что написанно в комментариях
|
|
||
| while (repeating_symbol != '\0'){ | ||
| if (repeating_symbol == array[read]){ | ||
| counter++; |
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.
здесь и далее корректней использовать префиксный инкремент
| while (repeating_symbol != '\0'){ | ||
| if (repeating_symbol == array[read]){ | ||
| counter++; | ||
| } 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.
лучше для if сделать короткую ветвь с continue:
- Не придется листать много кода, что увидеть действие перед переходом на следующую итерацию цикла, либо даже лучше переписать на
for - Можно будет убрать
elseи лишний уровень вложенности
| } | ||
|
|
||
| if (counter >= 10){ | ||
| counter = 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.
как будто поусловию некорректно сбрасывать счетчик, тогда мы начнем считать заного и можно насчитать другое число
| return; | ||
| } | ||
|
|
||
| std::vector<std::string> set_flags; |
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.
Выглядит очень не оптимально, во первых вектор будет вызывать реалокацию при push_back.
Да и будем перекладывать строки из вектора в поток
| // Константы для преобразования | ||
| constexpr long double IN_TO_CM = 2.54L; | ||
| constexpr long double FT_TO_IN = 12.0L; | ||
| constexpr long double M_TO_CM = 100.0L; |
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::cout << 1; | ||
| } else { | ||
| std::cout << 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.
Можно 5 строк заменитьтернарным оператор выводить в поток по условию 1 или 0, будет компактнее
| } else { | ||
| double x = static_cast<double>(-c) / b; | ||
| std::cout << std::defaultfloat << std::setprecision(6) << x; | ||
| } |
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::cout << std::defaultfloat << std::setprecision(6) << x; | ||
| } | ||
| } else { | ||
| long long discriminant = static_cast<long long>(b) * b - 4 * static_cast<long long>(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.
Понятно для чего так сделано, но не лучше хранить дискриминант в double в данном случае
|
|
||
| double CalculateRMS(double values[], size_t size) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| if (size <= 0 || values == nullptr){ return 0.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.
отсутствует пробел перед {
|
|
||
| double sum = 0; | ||
| for (size_t i=0; i < size; i++){ | ||
| sum+=std::pow(values[i], 2); |
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.
нет пробелов вокруг арифметических операторов и инициализации i
| if (size <= 0 || values == nullptr){ return 0.0; } | ||
|
|
||
| double sum = 0; | ||
| for (size_t i=0; i < size; 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.
Нужно использовать префиксный инкремент
|
|
||
| double ApplyOperations(double a, double b /* other arguments */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| double ApplyOperations(const double a, const double b, funcPtr* arr, size_t funcArraySize) { |
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.
наглядней было быиспользовать массив указателей на функцию, вместо указателя на указатель на функцию
| } | ||
|
|
||
| double cumulative_result = 0; | ||
| for (unsigned int i=0; i < funcArraySize; ++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.
пробелы вокруг =
| if (arr[i] == nullptr){ | ||
| continue; | ||
| } | ||
| cumulative_result+=arr[i](a, 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.
пробелы вокруг оператора +=
| указателя на начало и конец целочисленного массива, а также указатель на | ||
| функцию предикат, и возвращает указатель на найденный элемент. Если элемент | ||
| не найден, то возвращается указатель за последний элемент. | ||
| не найден, то возвращается указатель на последний элемент. |
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.
Это некорректное исправление так как, end не указывает на элемент и его нельзя разыменовывать
|
|
||
| if (last_element == 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.
вероятно это лишняя проверка, так как можно last_element присвоить end изначально и тогда если успешных проверок не было, просто вернется last_element с нужным значением
| { | ||
| if (predicate(*begin)){ | ||
| last_element = begin; | ||
| } |
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::setfill('0') << std::setw(2) | ||
| << static_cast<unsigned int>(bytes[i]); | ||
| } | ||
| std::cout << std::dec << std::endl; |
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.
Это задание было конечно на reinterpret_cast, что позволило бы не создавать буфер копию текущего значения. Но даже так, зачем в данном случае полное дублирование?
Лучше было написать ещё одну функцию, которая бы принимала буффер, размер и флаг и вызывалась бы из данных функций
| } | ||
| } | ||
| } | ||
| 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.
дублирование кода, в данном случае практически идентичное действие ветвей, за исключением некоторых моментов, можно переписать без дублирвоания
| T* temp = ptr2; | ||
| ptr2 = ptr1; | ||
| ptr1 = temp; | ||
| } |
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.
Можнобыло практически тоже самое сделать без шаблона
| double average = 0.0; | ||
| double standardDeviation = 0.0; | ||
|
|
||
| if (!numArray.empty()){ |
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.
пробела не хватает перед {
| /* return_type */ CalculateDataStats(/* args */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| } | ||
| DataStats CalculateDataStats(std::vector<int> numArray) { |
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.
Зачем мы копируем весь вектор? Там может быть очень много элемментов.
| average += delta / count; | ||
| delta2 = num - average; | ||
| standardDeviation += delta * delta2; | ||
| } |
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 month; | ||
| unsigned day; | ||
|
|
||
| Date(){this->year = 0u; this->month = 0u; this->day = 0u;} |
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.
Это очень плохо:
- Нет пробела перед
{ - Явно использовать указатель
thisне следует - Достаточно было указать значение по умолчанию для переменных и не пистаь оба конструктора, компилятор бы справился
| return true; | ||
| } | ||
| return false; | ||
| } |
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.
в данном случае без this (его правда не пишут) и с тернарным оператором было бы компакнее и лучше, а ещё лучше с std::tie
| if (!this->operator==(other)){ | ||
| return true; | ||
| } | ||
| return false; |
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.
это пишется в одну строку return !(*this == other);
| } | ||
| } | ||
|
|
||
| return false; |
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
| bool operator<(Date other) const { | ||
| if (this->year < other.year){ | ||
| return true; | ||
| } else if (this->year == other.year){ |
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.
else if лишний в данном случае в предыдущем условии есть return поэтому можно смело начинать с новой строки if
|
|
||
| StudentInfo(){} | ||
| StudentInfo(size_t id, char mark, int score, unsigned course, Date birth_date) : | ||
| id(id), mark(mark), score(score), course(course), birth_date(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.
конструкторы в данном случае лишние, компилятор справится и нужно использовать данную возможность
| if (this->operator<(other) || this->operator==(other)){ | ||
| return true; | ||
| } | ||
| return false; |
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
| } | ||
|
|
||
| return false; | ||
| } |
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.
оператор мог быть выражен через другие
| return os; | ||
| } | ||
|
|
||
| std::vector<std::string> flag_names; |
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.
не оптимально, создаем вектор с реалокациями, копим сначала строки а потом копируем их в поток
| /* return_type */ Filter(/* args */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| } | ||
| template <typename Predicat> |
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.
Predicate - пишим правильно или Pred
| } | ||
| template <typename Predicat> | ||
| void Filter(std::vector<int>& array, Predicat func) { | ||
| if constexpr (!std::is_same_v<Predicat, std::nullptr_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.
лишняя вложенность, это должно было быть коротким условием с явным return
| } | ||
|
|
||
| int lagging = 0; | ||
| for (size_t i=0; i < array.size(); ++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.
нет пробелов вокруг =
| template <typename Predicat> | ||
| void Filter(std::vector<int>& array, Predicat func) { | ||
| if constexpr (!std::is_same_v<Predicat, std::nullptr_t>) { | ||
| if (array.empty()){ |
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 Predicat, typename T> | ||
| std::vector<size_t> FindAll(const std::vector<T>& array, Predicat func) { | ||
| if constexpr (!std::is_same_v<Predicat, std::nullptr_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.
это должна бытькороткая ветка
| #include <vector> | ||
| #include <type_traits> // Для std::is_same_v | ||
|
|
||
| template <typename Predicat, 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.
это излишне, и как правило пишут сначала тип, а потом предикат, к тому же они в соответвтуещем порядке в аргументах функции
| #include <vector> | ||
| #include <utility> // Для std::pair и std::make_pair | ||
|
|
||
| std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator> MinMax(const std::vector<int>& vec) { |
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.
желательно ввести короткий псевдоним для константного итератора, так как тип громоздкий и дублируется. можно даже для наглядности ввести два псевдонима для MinIt, MaxIt, тогда будет понятно в каком порядке возвращаются итераторы (хотя в данном случае это излишне, но в более сложных функциях может пригодится такой подход)
| int y = 0; | ||
|
|
||
| Coord2D(){} | ||
| Coord2D(int x_val, int y_val) : 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.
Конструкторы лишнии
|
|
||
| Circle(){} | ||
| Circle(Coord2D c_val) : coord(c_val){} | ||
| Circle(Coord2D c_val, unsigned r_val) : coord(c_val), radius(r_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.
Конструкторы лишнии
| os << "circle[]"; | ||
| } else { | ||
| os << "circle[" << circle.coord << ", r = " << circle.radius << "]"; | ||
| } |
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 CircleRegion& region) { | ||
| os << (region.second ? '+' : '-') << region.first; | ||
| return 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.
можно сразу возвращать результат первой строки функции, но можно и так для читабельности
| std::ostream& operator<<(std::ostream& os, const CircleRegionList& list) { | ||
| if (list.empty()) { | ||
| os << "{}"; | ||
| } 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.
можно на коротком условии сразу написать return os << "{}"; и убрать else и уровень вложенности
| os << ",\n"; | ||
| } else { | ||
| os << "\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.
удобнее заменить на тернарный оператор
| result.push_back(from + i * step); | ||
| } | ||
|
|
||
| return result; |
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.
это хорошо
| return {}; | ||
| } | ||
|
|
||
| std::vector<int> result; |
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.
можно было зарезервировать под весь вектор, в конце все равно shrink_to_fit, так будет меньше реалокаций
|
@ilyamikhailov16 основные моменты
|
No description provided.