-
Notifications
You must be signed in to change notification settings - Fork 33
Шайхуллин Евгений #18
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
01_week/tasks/addition/addition.cpp
Outdated
| throw std::runtime_error{"Not implemented"}; | ||
| } No newline at end of file | ||
| int64_t res = static_cast<int64_t>(a); // Присвоение и приведение типов. | ||
| res = res + 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.
В данном случае это лишнее приведение типов, поскольку тип int64_t res то сработает implicit cast b к данному типу
01_week/tasks/addition/addition.cpp
Outdated
| } No newline at end of file | ||
| int64_t res = static_cast<int64_t>(a); // Присвоение и приведение типов. | ||
| res = res + static_cast<int64_t>(b); // Вычисление суммы и приведение типов. | ||
| return res; |
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.
Желательно написать вместо res сразу все выражение return a + b (с учетом каста одного из операндов), это будет нагляднее
01_week/tasks/rms/rms.cpp
Outdated
| double sum = 0.0; | ||
|
|
||
| if(0 == size) return 0.0;// | ||
| if(&values[0] == 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.
нет пробела после if
01_week/tasks/rms/rms.cpp
Outdated
| if(0 == size) return 0.0;// | ||
| if(&values[0] == nullptr) return 0.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.
нет пробела после for и перед {
01_week/tasks/rms/rms.cpp
Outdated
| if(&values[0] == nullptr) return 0.0; | ||
|
|
||
| for(size_t i = 0; i < size; i++){ | ||
| sum += values[i]*values[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.
нет пробелов вокруг оператора *
01_week/tasks/rms/rms.cpp
Outdated
| } No newline at end of file | ||
| double sum = 0.0; | ||
|
|
||
| if(0 == size) 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.
Лучше использовать литерал для беззнаковых 0u
01_week/tasks/rms/rms.cpp
Outdated
| double CalculateRMS(double values[], size_t size) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| } No newline at end of file | ||
| double sum = 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.
В данном случае либо sum создается рано, так как далее две короткие ветви выхода из функции, в которых sum не участвует и возвращается литерал, либо возвращать не литерал
01_week/tasks/rms/rms.cpp
Outdated
| if(0 == size) return 0.0;// | ||
| if(&values[0] == nullptr) return 0.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.
Постфиксный инкремент создает копию, в данном случае сразу можно менять i
01_week/tasks/rms/rms.cpp
Outdated
| double sum = 0.0; | ||
|
|
||
| if(0 == size) return 0.0;// | ||
| if(&values[0] == 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.
Это некорректная проверка приводящая к UB, values это уже указатель, поэтому если он nullptr то values[0] разыменовывает нулевой указатель.
Если быбыли соответствующие проверки в тестах, то этот код бы упал
| float fA = static_cast<float>(a); // Явное приведение типа int к float | ||
| float fB = static_cast<float>(b); // Явное приведение типа int к float | ||
| float fC = static_cast<float>(c); // Явное приведение типа int к float | ||
| float disc = static_cast<float>(c); // Явное приведение типа int к float |
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.
Слишком рано определяется множество переменных, дальше идут короткие ветки выхода из функций и если они срабатывают, то бесполезно создается множество переменных с преобразованием во float, во-вторых желательно было их не создавать, а выполнить некоторые преобразования по месту в выражениях и довериться неявному приведению
| } | ||
|
|
||
| // Если x = 0 | ||
| if(((a == 0) && (c == 0)) || ((b == 0) && (c == 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.
Есть излишнии скобки здесь и выше, труднее читать. в соответствии с приоритетом операторов скобки вокруг проверки на равенсво нулю можно опестить
|
|
||
| // Если a, b, c равны нулю – решений бесконечно много. | ||
| if((a == 0) && (b == 0) && (c == 0)){ | ||
| std::cout <<"infinite 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.
Вокруг операторов с двух сторон пробел по style guide
|
|
||
| if(a == 0) // Своего рода ускорение вычисления при a равном нулю | ||
| { | ||
| x1 = (-fC)/fB; |
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 // Решение через дискрименант | ||
| { | ||
| disc = fB * fB - 4 * fA * fC; |
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.
Достаточно было сделать float disc, а лучше double и не заводить переменные fA, fB, fC
| // определяем вывод в зависимости от X1 и X2 | ||
| if (x1 == x2) std::cout << std::setprecision(6) << x1 ; | ||
| else if(x1 < x2) std::cout << std::setprecision(6) << x1 << ' ' << x2; | ||
| else std::cout << std::setprecision(6) << x2 << ' ' << x1; |
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.
визуально очень плохо выглядит, так не делают
| } | ||
|
|
||
| x1 = (negativeUnit * fB - sqrt(disc))/(2*fA); | ||
| x2 = (negativeUnit * fB + sqrt(disc))/(2*fA); |
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.
Абсолютно не понял назначение целой переменно negativeUnit если можно использовать унарный минус. Нет std:: у sqrt. Нет пробелов вокруг операторов
| // Константы для преобразования | ||
| #define IN_TO_CM 2.54 | ||
| #define FT_TO_IN 12.0 | ||
| #define M_TO_CM 100.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.
Лучше использовать constexpr переменные
| } | ||
|
|
||
| constexpr double operator"" _m_to_cm(long double x) { | ||
| return static_cast<double>( x * M_TO_CM); // |
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.
лишний пробел перед 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.
Миллион лишних новых строк
| return static_cast<double>( x * FT_TO_IN); // преобразование фт в дюймы | ||
| } | ||
|
|
||
|
|
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.
Если есть комментарий достаточно одной новой строки
| throw std::runtime_error{"Not implemented"}; | ||
|
|
||
| // Защита от неверного значения размера в байтах. Размер в байтах должен быть от 1 до 8. | ||
| if(bytes == 0) 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.
отсутствие пробела и лишний пробел
| if(bytes == 0) return; | ||
| if(bytes > 8) return; | ||
|
|
||
| char buf[90] = {'\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.
Это излишне и не универсально, в данной задаче можно было сразу выводить в поток
| { | ||
| if(sizeBit != count) | ||
| { | ||
| buf[countBuf + count] = 39; |
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.
это magic value - от этого в коде принято избавляться, для представления данного символа нужно использовать escape-последовательности
| tempBit = 0x01; | ||
| while(temp > countBit) | ||
| { | ||
| countBit ++; |
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 long long sizeBit = bytes*8; // количество бит для вывода | ||
| unsigned long long countFour = 0; | ||
| unsigned long long countBuf = 0; // счетчик для элементов массива | ||
| unsigned long long countBit = 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.
много лишних переменных и неоргонизованного кода, задача решается более компактно
| if(data > static_cast<uint8_t>(CheckFlags::ALL)) return; | ||
| if(data != 0) | ||
| { | ||
| if(data & static_cast<uint8_t>(CheckFlags::TIME)){ |
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
| void PrintCheckFlags(CheckFlags flags) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
|
|
||
| char buf[40] = {'\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.
Это неудобно, достаточно было выводить в поток сразу часть строки
| i++; | ||
| } | ||
|
|
||
| buf[i++] = 'T'; buf[i++] = 'I'; buf[i++] = 'M'; buf[i++] = 'E'; |
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 <stdexcept> | ||
|
|
||
| // !!!! ВАЖНО !!!! Изначальное объявление функции изменено в части инициализации передаваемого элемента с «char delimiter = ' '» на «char delimiter». | ||
| size_t CharChanger(char array[], size_t size, char delimiter) { |
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.
Это некорректное исправление!
В тестах не было проверки на разделитель по умолчанию, но он должен быть задан в соответствии с сигнатурой функции по заданию
03_week/tasks/find_all/find_all.cpp
Outdated
| /* return_type */ FindAll(/* args */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| } No newline at end of file | ||
| std::vector<size_t> FindAll(const std::vector<int>& data, bool(*op)(int)) |
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.
лишний пробел
03_week/tasks/minmax/minmax.cpp
Outdated
|
|
||
| /* return_type */ MinMax(/* args */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| std::pair<std::vector<int>::iterator, std::vector<int>::iterator> MinMax(std::vector<int>& data) { |
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.
Для длинных типов лучше ввести псевдоним, в данно случае можно для итераторов псевдоним добавить
Когда производится поиск миниму и максимума никогда не подразумевается возможность изменение контейнера, поэтому в качестве входного аргумента должен быть const контейнер
03_week/tasks/minmax/minmax.cpp
Outdated
| // проверка, что контейнер не пуст | ||
| if(data.size() == 0){ // контейнер пуст | ||
| // return {begin, begin}; // Используем uniform initialization | ||
| return std::pair<std::vector<int>::iterator, std::vector<int>::iterator>(begin, 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.
длинно
03_week/tasks/minmax/minmax.cpp
Outdated
| } | ||
|
|
||
| // перегрузка функции | ||
| std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator> MinMax(const std::vector<int>& data) { |
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.
Вроде нигде не нужно менять элемент по интератору в услвоию, поэтому две функции излишне
Поэтому нужно оставить одну. В любом случае необходимо избавляться от полного дублирования
| // Оператор вывода для CircleRegion | ||
| std::ostream& operator<<(std::ostream& os, const CircleRegion& сircleRegion) { | ||
| // работа с контейнером "pair" | ||
| // первый элемент типа Circle, второй bool |
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.
в целом такие комментарии излишние, поскольку CircleRegion это пара соответствующих занчений
03_week/tasks/range/range.cpp
Outdated
| throw std::runtime_error{"Not implemented"}; | ||
| std::vector<int> Range(int from, int to, int step = 1) { | ||
|
|
||
| if(from == to) return std::vector<int>(); // проверка равенства начала и конца интервала |
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.
@9617771614, основные проблемы
- Разыменование nullptr из-за некорректной проверки на nullptr (01_week)
- Использование постфиксного инкремента в циклах
- Излишние явные приведения типов, не используются неявные касты
- Создание избыточных переменных, неэффективный код
- Неаккуратный код: проблемы со стилем, лишние строки и пробелы, разный стиль
- Дублирование функциональности
Stack
Временно отключаю контроль задачь недели 3
Временно отключаю контроль задачь недели 2 иначе в проверке куча строк.
Временно отключаю контроль задачь недели 1 иначе в проверке куча строк.
|
|
||
| void Swap(Stack& other); // меняем местами элементы | ||
|
|
||
| // определение для == |
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.
лишний комментарий
|
|
||
| // определение для != | ||
| bool operator!=(const Stack& x) const {return !(data == x.data);} | ||
|
|
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.
обычно методы группирует без лишних пустых строк, например операторы сравнения можно объявить без пустой строки, также для методов доступа, например, методов изменения
|
|
||
| // ---- Конструкторы ----- | ||
| explicit RingBuffer(size_t capacity); // Конструктор от емкости | ||
| RingBuffer(size_t capacity, int initialValue); // Конструткор от емкасти и начального значения |
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.
емкОсти, вместимости
| bool Empty() const {return countElem == 0;} | ||
| bool Full() const {return countElem == buf.capacity();} | ||
| size_t Size() const{return countElem;} | ||
| size_t Capacity() const{return buf.capacity();} |
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 NextIndex(size_t i) const { | ||
| if((i + 1) >= buf.capacity()) return 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 не пробела после if
| } | ||
|
|
||
| RingBuffer::RingBuffer(size_t capacity, int initialValue) { | ||
|
|
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.
лишняя строка
| buf.resize(capacity); | ||
| prevElem = 0; | ||
| nextElem = 0; | ||
| countElem = 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.
лучше сделать в списке инициализации. для буфера предварительный reserve излишний в данном случае
| prevElem = 0; | ||
| nextElem = 0; | ||
| countElem = 0; | ||
| for (size_t i = 0; i < capacity; ++i) Push(initialValue); |
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.
правильнее все действия выполнить в списке инициализации, для buf воспользоваться конструктором
| nextElem = 0; | ||
| countElem = 0; | ||
|
|
||
| for (int value : init) Push(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.
аналогично, все можно сделать в списке инициализации
| nextElem = NextIndex(nextElem); | ||
| } else { | ||
| buf[nextElem] = value; | ||
| nextElem = NextIndex(nextElem); |
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.
общие действия которые выполняются в любом случае, лучше вынести, чтобы не дублировать
| buf[nextElem] = value; | ||
| prevElem = NextIndex(prevElem); | ||
| nextElem = NextIndex(nextElem); | ||
| } 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.
лучше убрать else сделать одну короткую ветвь с return
| } | ||
| } | ||
|
|
||
| bool RingBuffer::TryPush(int 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.
код Push и TryPush достаточно похож, так что можно было переиспользовать один в другом
|
|
||
|
|
||
|
|
||
|
|
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.
лишние пустые строки
18thday
left a comment
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.
@9617771614 не все задания получилось сделать, по тем что есть код хороший:
- лучше использовать список инициализации в конструкторе
- убрать дублирование
No description provided.