Skip to content

Conversation

@18thday
Copy link
Contributor

@18thday 18thday commented Dec 24, 2025

No description provided.

throw std::runtime_error{"Not implemented"};
} No newline at end of file

return static_cast<int64_t>(a) + 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.

Лишний каст, после приведения одной переменной, вторая приведется неявно, необходимо понимать и использовать данные возможности языка для лаконичности

#include <cstddef>
#include <stdexcept>

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.

Не нужно изменять сигнатуру функции если не просят. В данном случае это некорректное изменение, так как теряется часть функциональности

// Приведения текущего символа к определенным типам: пробел, число или ASCII символ
bool isSpace = std::isspace(static_cast<unsigned char>(currentChar)) != 0;
bool isDigit = std::isdigit(static_cast<unsigned char>(currentChar)) != 0;
bool isAlpha = std::isalpha(static_cast<unsigned char>(currentChar)) != 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.

Зачем создавать переменные если переменная:

  1. Используется единожды
  2. Если используется, то другие не используются (на каждом шаге выполняются все проверки)

// Подсчёт длины последовательности одинаковых символов
size_t nextPos = readPos + 1;
while (nextPos < size - 1 && array[nextPos] == currentChar) {
nextPos++;
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 (isSpace) {
array[writePos++] = 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.

более выразительно переписать с использованием continue и следовательно убрать вложенность и непосредственно следом идущий else, так как иначе приходится листать весь блок кода else чтобы понять, будет ли ещё что-то изменяться

throw std::runtime_error{"Not implemented"};
}
uint8_t value = static_cast<uint8_t>(flags);
uint8_t all_bits = static_cast<uint8_t>(CheckFlags::ALL);
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;
}

const std::pair<CheckFlags, const char*> flag_names[] = {
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.

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



constexpr long double CM_TO_M = 0.01L;
constexpr long double M_TO_CM = 1.0L / CM_TO_M;
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 long double IN_TO_CM = IN_TO_M * 100.0L;
constexpr long double CM_TO_IN = 1.0L / IN_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.

лишняя строка


void PrintBits(long long value, size_t bytes) {
throw std::runtime_error{"Not implemented"};
void PrintBits(long long value, size_t bytes) {
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


// Сдвиг, чтобы напечатать младшие байты
ULL mask = (bytes == BYTES_IN_LONG_LONG)
? ~0ULL
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Как-то неожиданно отступ стал 2 пробела вместо принятых 4. Обычно пишут в одном стиле, когда сами пишут

}

if(a != 0) { // two roots
int discriminant = 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.

то 2, то 4 пробела


cout << setprecision(6);
if(discriminant > 0) {
double discriminantRoot = sqrt(discriminant);
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::sqrt

cout << setprecision(6);
if(discriminant > 0) {
double discriminantRoot = sqrt(discriminant);
double x1 = (-b - discriminantRoot) / (2.0*a);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

пробелы вокруг *

long double sumOfSquares = 0;

for(size_t i = 0; i < size; ++i) {
double &value = 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.

const double&

double ApplyOperations(double a, double b /* other arguments */) {
throw std::runtime_error{"Not implemented"};
} No newline at end of file
double ApplyOperations(double a, double b, double (**ops)(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.

Для наглядности хотелось, чтобы это был массив укзателей на функцию

double sum = 0.0;
for (size_t i = 0; i < size; ++i) {
if (ops[i] == nullptr) {
continue; // �� ��������� ��������, ���� ��������� ������� ����� nullptr
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Вероятно нужно поправить кодировку на UTF-8

} No newline at end of file
void PrintMemory(double value, bool reverse = false) {
using std::cout, std::hex, std::uppercase, std::setw, std::setfill;
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(&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(value) далее можно было вызывать одну общую функцию, и переиспользовать код

previousCharacter = currentCharacter;
}

// �������� ���������� ��������
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 longestStringStart;
}

char* FindLongestSubsequence(char* begin, char* end, size_t& 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.

Хорошее применение

}


// ������ � �������������
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 += reversed ? -1 : 1;
}

// �� ��� ������� ������ ���������� �� ����� ������, ���������
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Кодировка

// ������ ��� ����������� �� ���������� ���������
cout << "[";
if (limit == 0 || limit >= count) {
if (reversed == false) {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

!reversed - лучше подходит

if (ptr != first) cout << ", ";
cout << *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.

тут практически полное дублирование, можно вынести в функцию, либо производить проверку reversed ? --ptr : ++ptr


stats.avg = sum / data.size();
double variance = (sum_of_squares / data.size()) - (stats.avg * stats.avg);
variance = variance >= 0.0 ? variance : 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.

лишнее присваивание variance = variance

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 , просто в операндах можно связывать как lhs так и rhs, чтобы выразить меньше и больше, а сам оператор в выражении return останется <

if (!first) os << ", ";
os << "DEST";
first = false;
}
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 <vector>
#include <utility>

std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator> MinMax(const std::vector<int>& vec) {
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>::const_iterator

++it;
}

while ((it + 1) < vec.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.

лишние скобки для it + 1

std::ostream& operator<<(std::ostream& os, const CircleRegionList& list) {
if (list.empty()) {
os << "{}";
} 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.

лучше внутри if добавить return и не делать вложенность внутрь else. По возможности стараются избегать else

count = (to - from + step - 1) / step;
} else {
count = (to - from + step + 1) / 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> result;
result.reserve(count);

bool isForward = step > 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.

тем более тут все равно используется отдельная переменная для этого.
Но можно и без неё если используется в одном месте

}
std::vector<int> Unique(const std::vector<int>& vec) {
if (vec.empty()) {
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.

{} - более выразительно с учетом известного возвращаемого типа

if (vec[i] != vec[i - 1]) {
++unique_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.

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

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.

@Andrey23525, код понравился, аккуратно, выразитльно, задачи решены достаточно оптимально, указал некоторые моменты

size_t capacity_ = 0;
size_t size_ = 0;
size_t head_ = 0; // индекс для добавления (Front)
size_t tail_ = 0; // индекс для удаления (Back)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

можно было обойтись меньшим количество позиций, например capacity можно брать у вектора,если его корректно поддерживать, не обязательно но можно было отказаться от head_ или tail_ зная size и capacity

, size_(0)
, head_(0)
, tail_(0) {
data_.resize(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_(capacity_)
, head_(0)
, tail_(0) {
data_.resize(capacity_, 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.

аналогично, можно воспользоваться соответствующим конструктором

size_t idx = 0;
for (int value : init) {
data_[idx++] = 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.

лишний код, можно сконструировать вектор из init


};
Queue::Queue(const std::vector<int>& vec) {
input_stack_ = vec;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

можно было перенести в список инициализации


class Queue {
Queue::Queue(size_t capacity) {
input_stack_.reserve(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.

почему бы не зарезервировать память под output_stack_

temp.push_back(s.top());
s.pop();
}
std::reverse(temp.begin(), temp.end());
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.

почему сразу не складывать в otput_stack_ в подходящем порядке?

}

int& Queue::Back() {
if (input_stack_.empty() == false) {
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() не принято явно сравнивать с булевой переменной, для этого есть !empty()

}

int& Queue::Front() {
TransferIfNeeded();
Copy link
Contributor Author

Choose a reason for hiding this comment

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

а почему нельзя поступить аналогично методу Back?

}

Queue a = *this;
Queue b = 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.

мы знаем внутреннее устройство контейнера, создавать копии дорого

double new_real = real_ * other.real_ - imag_ * other.imag_;
double new_imag = real_ * other.imag_ + imag_ * other.real_;
real_ = new_real;
imag_ = new_imag;
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.

@Andrey23525 отметил некоторые моменты:

  • хороший код
  • лишнее копирование при сравнении Queue, можно избежать
  • лишнии поля в RingBuffer, можно на 2 меньше

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