Skip to content

Conversation

@18thday
Copy link
Contributor

@18thday 18thday commented Dec 24, 2025

No description provided.

@18thday 18thday marked this pull request as ready for review December 24, 2025 06:29
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); // Вычисление суммы и приведение типов.
Copy link
Contributor Author

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 к данному типу

} No newline at end of file
int64_t res = static_cast<int64_t>(a); // Присвоение и приведение типов.
res = res + static_cast<int64_t>(b); // Вычисление суммы и приведение типов.
return res;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Желательно написать вместо res сразу все выражение return a + b (с учетом каста одного из операндов), это будет нагляднее

double sum = 0.0;

if(0 == size) return 0.0;//
if(&values[0] == nullptr) return 0.0;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет пробела после if

if(0 == size) return 0.0;//
if(&values[0] == nullptr) return 0.0;

for(size_t i = 0; i < size; i++){
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет пробела после for и перед {

if(&values[0] == nullptr) return 0.0;

for(size_t i = 0; i < size; i++){
sum += values[i]*values[i];
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет пробелов вокруг оператора *

} No newline at end of file
double sum = 0.0;

if(0 == size) return 0.0;//
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше использовать литерал для беззнаковых 0u

double CalculateRMS(double values[], size_t size) {
throw std::runtime_error{"Not implemented"};
} No newline at end of file
double sum = 0.0;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В данном случае либо sum создается рано, так как далее две короткие ветви выхода из функции, в которых sum не участвует и возвращается литерал, либо возвращать не литерал

if(0 == size) return 0.0;//
if(&values[0] == nullptr) return 0.0;

for(size_t i = 0; i < size; i++){
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Постфиксный инкремент создает копию, в данном случае сразу можно менять i

double sum = 0.0;

if(0 == size) return 0.0;//
if(&values[0] == nullptr) return 0.0;
Copy link
Contributor Author

@18thday 18thday Dec 24, 2025

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
Copy link
Contributor Author

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)))
Copy link
Contributor Author

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";
Copy link
Contributor Author

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;
Copy link
Contributor Author

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;
Copy link
Contributor Author

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;
Copy link
Contributor Author

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);
Copy link
Contributor Author

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
Copy link
Contributor Author

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); //
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишний пробел перед x





Copy link
Contributor Author

@18thday 18thday Dec 24, 2025

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); // преобразование фт в дюймы
}


Copy link
Contributor Author

@18thday 18thday Dec 24, 2025

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;
Copy link
Contributor Author

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'.
Copy link
Contributor Author

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;
Copy link
Contributor Author

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 ++;
Copy link
Contributor Author

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;
Copy link
Contributor Author

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)){
Copy link
Contributor Author

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'};
Copy link
Contributor Author

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';
Copy link
Contributor Author

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) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это некорректное исправление!
В тестах не было проверки на разделитель по умолчанию, но он должен быть задан в соответствии с сигнатурой функции по заданию

/* 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))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишний пробел


/* 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) {
Copy link
Contributor Author

@18thday 18thday Dec 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для длинных типов лучше ввести псевдоним, в данно случае можно для итераторов псевдоним добавить

Когда производится поиск миниму и максимума никогда не подразумевается возможность изменение контейнера, поэтому в качестве входного аргумента должен быть const контейнер

// проверка, что контейнер не пуст
if(data.size() == 0){ // контейнер пуст
// return {begin, begin}; // Используем uniform initialization
return std::pair<std::vector<int>::iterator, std::vector<int>::iterator>(begin, begin);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

длинно

}

// перегрузка функции
std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator> MinMax(const std::vector<int>& data) {
Copy link
Contributor Author

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
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в целом такие комментарии излишние, поскольку CircleRegion это пара соответствующих занчений

throw std::runtime_error{"Not implemented"};
std::vector<int> Range(int from, int to, int step = 1) {

if(from == to) return std::vector<int>(); // проверка равенства начала и конца интервала
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{} - более короткий вариант пердпочтительнее

Copy link
Contributor Author

@18thday 18thday left a 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)
  • Использование постфиксного инкремента в циклах
  • Излишние явные приведения типов, не используются неявные касты
  • Создание избыточных переменных, неэффективный код
  • Неаккуратный код: проблемы со стилем, лишние строки и пробелы, разный стиль
  • Дублирование функциональности

 Временно отключаю контроль задачь недели 3
 Временно отключаю контроль задачь недели 2 иначе в проверке куча строк.
 Временно отключаю контроль задачь недели 1 иначе в проверке куча строк.

void Swap(Stack& other); // меняем местами элементы

// определение для ==
Copy link
Contributor Author

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);}

Copy link
Contributor Author

@18thday 18thday Jan 21, 2026

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); // Конструткор от емкасти и начального значения
Copy link
Contributor Author

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();}
Copy link
Contributor Author

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;
Copy link
Contributor Author

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) {

Copy link
Contributor Author

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;
Copy link
Contributor Author

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);
Copy link
Contributor Author

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);
Copy link
Contributor Author

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);
Copy link
Contributor Author

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 {
Copy link
Contributor Author

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) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

код Push и TryPush достаточно похож, так что можно было переиспользовать один в другом





Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишние пустые строки

Copy link
Contributor Author

@18thday 18thday left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@9617771614 не все задания получилось сделать, по тем что есть код хороший:

  • лучше использовать список инициализации в конструкторе
  • убрать дублирование

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants