Skip to content

Conversation

@18thday
Copy link
Contributor

@18thday 18thday commented Jan 23, 2026

No description provided.


DataStats CalculateDataStats(const std::vector<int>& data) {
DataStats result;
size_t n = data.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.

лучше не использовать переменные из одного символа

sum += 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.

кодировка поехала, UTF-8 у файла должно быть


Date() : year(0), month(0), day(0) {}

Date(unsigned y, unsigned m, unsigned d) : year(y), month(m), day(d) {}
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 !(lhs < rhs);
}

int mark_priority(char 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.

Это дишняя функция, символы имеет целочисленное значение, и их можно сравнивать. Функцию придется менять в случае добавления оценки, например F или Y или ещё какого-то статуса, поэтому лучше так не делать а сравнивать символы напрямую, тогда при измененнии возможных значений логика не сломается и изменения не нужны будут

case 'B': return 4;
case 'C': return 3;
case 'D': return 2;
case 'Z': return 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.

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

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 местами, то в каком операнде операции < они находятся, знак сравнения изменится на противоположный, таким образом когда упорядоченность можно выразить через < > без дополнительных особых условий, пользуются std::tie

ALL = TIME | DATE | USER | CERT | KEYS | DEST
};

constexpr uint8_t MASK = 0x3F;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

не очень хороший вариант, поскольку есть ALL и значение 0x3F корректнее заменить с егоиспользованием или по месту использовать без переменной

if ((flags & CheckFlags::DEST) != CheckFlags::NONE) {
if (!first) os << ", ";
os << "DEST";
}
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>
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>::iterator, std::vector<int>::iterator>
MinMax(std::vector<int>& vec) {
Copy link
Contributor Author

@18thday 18thday Jan 23, 2026

Choose a reason for hiding this comment

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

  • это лишняя функция, так как по условию не было требования возожности изменения по итератору значений Min Max
  • передача по обычной ссылке без константности вводит в заблуждение, говоря пользователю, что вектор может поменяться внутри, но это не так

}
}

return {min_it, max_it};
Copy link
Contributor Author

Choose a reason for hiding this comment

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

к тому же тут полное дублирование,

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

лучше инициализировать сразу переменную n, используя тернарный оператор при -1 +1

result.reserve(vec.size());


result.push_back(vec[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.

почему не сделать цикл с 0?

#include <vector>

std::vector<int> Range(int from, int to, int step) {
if (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.

лишний отступ


result.reserve(vec.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 mag = Magnitude();
double phase = Phase();
real_ = mag * std::cos(phase);
imag_ = mag * std::sin(phase);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

не понял зачем тут тело цикла?

Phasor Inv() const {
double mag = Magnitude();
if (mag == 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.

кодировка

};

Phasor operator+(const Phasor& lhs, const Phasor& rhs) {
Phasor result = lhs;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

можно тогда было сразу принимать копию

}
}

Queue(std::initializer_list<int> il) : in_(il) {}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

два раза копируем в il и в in

int& Front() {
if (Empty()) {
static int dummy;
return dummy;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

это лишнее

}

Queue q1 = *this;
Queue q2 = 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.

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

size_t head_ = 0;
size_t tail_ = 0;
size_t size_ = 0;
size_t capacity_ = 0;
Copy link
Contributor Author

@18thday 18thday Jan 23, 2026

Choose a reason for hiding this comment

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

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

explicit RingBuffer(size_t capacity) {
ensure_nonzero_capacity(capacity);
capacity_ = capacity;
buffer_.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.

это лишнее, в данном случае лучше воспользоваться списком инициализации, а корректное значение capacity можно получить использовав тернарный оператор, а ещё лучше std::max(1, capacity)

buffer_.resize(capacity_);
}

RingBuffer(size_t capacity, int initial_value) : RingBuffer(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.

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

std::fill(buffer_.begin(), buffer_.end(), initial_value);
}

RingBuffer(std::initializer_list<int> init) {
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::initializer_list

void Push(int value) {
if (Full()) {
buffer_[tail_] = value;
advance(tail_);
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 (Full()) {
return false;
}
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.

получается в TryPush дважды проверка Full, непосредственно в теле метода и внутри Push, не эффективно

void Pop() {
if (!Empty()) {
advance(head_);
--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.

лучше сделать короткую ветвеь с return для пустого буфера

bool operator!=(const Stack& other) const;

private:
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.

}; - на новой строке

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.

@Rygrotten неплохой код, но не все задачи решены по 1-3, отметил следующие моменты

  • дублирование кода
  • неоптимальное сравнение Queue с двойным копированием
  • не используются списки инициализации (лишний код в теле конструкторов)
  • лишние поля в RingBuffer

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