Skip to content

Conversation

@18thday
Copy link
Contributor

@18thday 18thday commented Jan 21, 2026

No description provided.

Sergey Bobrovskikh and others added 30 commits November 22, 2025 22:49

double a_ = static_cast<double>(a);
double b_ = static_cast<double>(b);
double c_ = static_cast<double>(c);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

это лишнее, вариант выше был лучше, дальше также

// Один корень линейного уравнения
PrintRoot(-c_ / b_);
}
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.

лучше не плодить вложенные ветвления, короткие условия как в начале лучше, немного больше может получится проверок на 0, но это не страшно

return;
}

double D = b_*b_ - 4*a_*c_;
Copy link
Contributor Author

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

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

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

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

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) {
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 и 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]);
}
}
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.

можно было попробовать избавиться от дублирование, тело одинаковое

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

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++;
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 (const char* ptr = begin + 1; ptr < end; ++ptr) {
if (*ptr == *(ptr - 1)) {
current_count++;
} 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.

лучше выше написать continue, а тут избавится от вложенности лишнего else

longest_ptr = current_ptr;
}
count = max_count;
return const_cast<char*>(longest_ptr);
Copy link
Contributor Author

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

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

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

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

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

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

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;
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::tie так как в если менять местами поля для rhs lhs в правом и левом операнде, при одном знаке <, можно некоторые поля сравнивать на <, а некотоыре на >


for (size_t i = 0; i < vec.size(); ++i) {
if (predicate(vec[i])) {
if (i != write_index) {
Copy link
Contributor Author

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

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

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) {}
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 radius = 1;
Circle() : coord(), radius(1) {} // Default
explicit Circle(Coord2D c, unsigned r = 1) : coord(c), radius(r) {}
Circle(unsigned r) : coord(), radius(r) {}
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::ostream& operator<<(std::ostream& os, const CircleRegionList& circle_vector) {
os << '{';
Copy link
Contributor Author

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;
}
}
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::vector<int> Unique(std::vector<int> sorted_nums) {
std::vector<int> unique_nums;
if(sorted_nums.empty()) {return unique_nums;}
Copy link
Contributor Author

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

Choose a reason for hiding this comment

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

лучше убрать вложенность previous == num - > continue

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.

@WhoAmI1909 отметил следующие моменты

  • дублирование кода
  • UB const_cast
  • местами лишние переменные
  • не все задачи решены

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