-
Notifications
You must be signed in to change notification settings - Fork 33
Войкина Варвара #13
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?
Войкина Варвара #13
Conversation
…adratic, rms tasks
| int64_t Addition(int a, int b) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| } No newline at end of file | ||
| return (int64_t)a + (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.
C-style cast не следует использовать в C++ коде, в данном случае нужен один static_cast.
Лишний каст, второй операнд не следует приводить явно, так как он бы преобразовался с помощью неявного каста. Принято использовать такую возможность и не писать явный каст самостоятельно второй раз
| {CheckFlags::CERT, "CERT"}, | ||
| {CheckFlags::KEYS, "KEYS"}, | ||
| {CheckFlags::DEST, "DEST"} | ||
| }; |
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 double operator"" _ft_to_in(long double feet) { | ||
| return static_cast<double>(feet) * 12.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.
12.0 это тоже magic value, которое не принято оставлять в коде
| constexpr double METER_TO_FOOT = 1.0 / FOOT_TO_METER; | ||
| constexpr double METER_TO_INCH = 1.0 / INCH_TO_METER; | ||
| constexpr double CM_TO_METER = 0.01; | ||
| constexpr double METER_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.
лучше поместить в namespace, можно безымянный
| return static_cast<double>(feet) * FOOT_TO_METER; | ||
| } | ||
|
|
||
| constexpr double operator"" _ft_to_m(unsigned long long feet) { |
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.
в данном случае это излишнее дублирование, так как неявно сконвертировался бы long double и достаточно одной функции в нашем случае
| std::cout << "0b"; | ||
|
|
||
| int total_bits = static_cast<int>(bytes) * 8; | ||
| for (int i = total_bits - 1; i >= 0; 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.
префиксная версия декремента должна быть
| std::cout << "infinite solutions"; | ||
| } | ||
| 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.
лучше особые случаи выделять отдельно и делать короткие ветви с return, немного больше станет проверок на ноль, но сильно повысится читаемость
|
|
||
| double mean_of_squares = sum_of_squares / size; | ||
|
|
||
| return std::sqrt(mean_of_squares); |
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.
можно результат деления подставить в выражение, так как mean_of_squares не используется
| @@ -1,6 +1,12 @@ | |||
| #include <stdexcept> | |||
|
|
|||
| typedef double (*MathOperation)(double, double); | |||
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.
в С++ принято использовать using
| throw std::runtime_error{"Not implemented"}; | ||
| } No newline at end of file | ||
| const int* FindLastElement(const int* begin, const int* end, Predicate predicate) { | ||
| if (begin == nullptr || end == nullptr || begin > end || predicate == nullptr) { |
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 || !predicate
| for (size_t i = 0; i < sizeof(T); ++i) { | ||
| std::cout << std::hex << std::setfill('0') << std::setw(2) | ||
| << std::uppercase << 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.
в данном случае это дублирование кода, можно перепистаь чтобы избавиться от него
| count = static_cast<int>(end - begin); | ||
| } else { | ||
| count = static_cast<int>(begin - 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.
тернарный оператор при инициализации count сократил бы 6 строк до 1
| if (begin == end) { | ||
| std::cout << "[]\n"; | ||
| 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.
это все можно отнести к невалидным данным, поскольку конкретная причина не сообщается а результат действия одинаковый, нужно было объединить с условием выше
| current = begin + i; | ||
| } else { | ||
| current = begin - 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.
тернарный оператор, или до начала цикла определять step который прибавлятьк i, на каждом шаге не нужно согдавать current и определять её значение, можно смещатьтекущий, если адать его вне цикла, в общем много вариантов как сделать оптимальнее
| } | ||
|
|
||
| std::cout << *current; | ||
| elements_in_current_line++; |
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.
постфиксный нужен только там, где нужна копия, в остальных случаях везде используется префиксный
| } | ||
|
|
||
| char* FindLongestSubsequence(char* begin, char* end, size_t& count) { | ||
| return FindLongestSubsequenceImpl(begin, end, 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.
зачем тогда писать Impl ? если можно сразу ссделать шаблон
| tmp.push_back(st.top()); | ||
| st.pop(); | ||
| } | ||
| for (auto it = tmp.rbegin(); it != tmp.rend(); ++it) { |
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.
зачем два цикла? почему сразу не писать в out_?
| if (a.Size() != b.Size()) { | ||
| return false; | ||
| } | ||
| return a.ToVector() == b.ToVector(); |
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; | ||
| } | ||
|
|
||
| Queue* self = const_cast<Queue*>(this); |
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 при вызове от константного объекта. Пересмотреть дизайн метода Front()
| size_ = buffer_.size(); | ||
| if (size_ == 0) { | ||
| buffer_.resize(1); | ||
| size_ = 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.
при выполнении условия известно, что размер 0
|
|
||
| bool TryPush(int value) { | ||
| if (Full()) return false; | ||
| 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.
дважды проверяется Full
| bool Empty() const { return size_ == 0; } | ||
| bool Full() const { return size_ == buffer_.size(); } | ||
| size_t Size() const { return size_; } | ||
| size_t Capacity() const { return buffer_.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.
может лучше 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.
@VaryVA основные моменты:
- нет задач 3 недели
- C-style cast
- неоптимальное сравнение Queue
- UB const_cast в Queue, нарушение семантики const метод модифицирует объект
No description provided.