Skip to content

Conversation

@vova22013
Copy link

No description provided.

@18thday 18thday changed the title hw_01 Кузнецов Владимир Jan 20, 2026

for (; it != end - 1; ++it){
if (*it == *(it + 1)) ++curr_count;
else {
Copy link
Contributor

Choose a reason for hiding this comment

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

лучше выше добавить continue под if и не делать дополнительный уровень вложенности из-за else для кода ниже

throw std::runtime_error{"Not implemented"};
void PrintArray(const int* begin, const int* end, size_t limit = 0) {
auto _start = const_cast<int*>(begin);
auto _end = const_cast<int*>(end);
Copy link
Contributor

Choose a reason for hiding this comment

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

UB const_cast


for (size_t i = 0; i < v_size; ++i) {
sum_sq += static_cast<long long>(vec[i]) *
static_cast<long long>(vec[i]);
Copy link
Contributor

Choose a reason for hiding this comment

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

достаточно одного вместо двух и лучше писать в одной строке

if (date1.day > date2.day) return true;
}
}
return false;
Copy link
Contributor

Choose a reason for hiding this comment

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

в данной задаче везеде можно использовать std::tie от нескольких полей, что позволяет запистаь условия в одну строку и так правильнее делать

bool operator!=(const Date& date1, const Date& date2) {
return date1.year != date2.year ||
date1.month != date2.month ||
date1.day != date2.day;
Copy link
Contributor

Choose a reason for hiding this comment

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

можно легко вырзаить через предыдущий определенный оператор

if (date1.day < date2.day) return true;
}
}
return false;
Copy link
Contributor

Choose a reason for hiding this comment

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

как правило определяют оператор < и ==, а все остальные выражают через данные операторы

}
if ((static_cast<CheckFlags>(res) == CheckFlags::NONE) || (!flag1 && !flag2)) {
return false;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

много лишнего в коде

if (func(*it)) {
auto temp = *it;
*it = *last_correct_it;
*last_correct_it = temp;
Copy link
Contributor

Choose a reason for hiding this comment

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

тут видимо надо было std::swap применить, либо перезаписывать непосредственно

#include <vector>

typedef std::vector<int> vec_i_t;
typedef std::vector<int>::const_iterator cit_t;
Copy link
Contributor

Choose a reason for hiding this comment

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

для C++ предпочтительнее использовать using

#include <stdexcept>
#include <vector>

typedef std::vector<int> vec_i_t;
Copy link
Contributor

Choose a reason for hiding this comment

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

это лишнее

std::vector<int> Range(int from, int to, int step = 1) {
if ((to == from) ||
((to > from) && (step <= 0)) ||
((from > to) && (step >= 0)))
Copy link
Contributor

Choose a reason for hiding this comment

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

можно было проверить шаг и по резульату проверки вернуть из тернарного оператора нужный результат сравнения to from

}

Phasor& Phasor::operator-=(const Phasor& other) {
double real = this->Real() - other.Real();
Copy link
Contributor

Choose a reason for hiding this comment

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

this-> не следует использовать внутри класса, это лишнее

Queue::Queue(const std::vector<int>& input_vec) : m_in_vec(input_vec) {};

Queue::Queue(const std::initializer_list<int>& input_list)
: m_in_vec(static_cast<std::vector<int>>(input_list)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

static_cast тут зачем?

m_out_vec.pop_back();
return true;
}
else {
Copy link
Contributor

Choose a reason for hiding this comment

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

это лишняя вложенность в ветви выше уже есть return

}
else {
SwapVecs(other.m_out_vec, m_out_vec, min_size_out);;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

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

if (this == &other) return true;

std::vector<int> queue_this(m_in_vec.size() + m_out_vec.size());
std::vector<int> queue_other(other.m_in_vec.size() + other.m_out_vec.size());
Copy link
Contributor

Choose a reason for hiding this comment

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

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

std::vector<int> queue_this(m_in_vec.size() + m_out_vec.size());
std::vector<int> queue_other(other.m_in_vec.size() + other.m_out_vec.size());

if (queue_this.size() != queue_other.size()) return false;
Copy link
Contributor

Choose a reason for hiding this comment

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

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

return true;
}

bool Queue::operator!=(const Queue& other) const {
Copy link
Contributor

Choose a reason for hiding this comment

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

выражается через функцию выше, код не дублируется

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

private:
friend void SwapVecs(std::vector<int>& v1, std::vector<int>& v2, size_t min_size);
Copy link
Contributor

Choose a reason for hiding this comment

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

это лишнее

int trash = std::rand();
int& ref_trash = trash;
return ref_trash;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

лишний код


void Stack::Clear() {
stack.resize(0);
stack.shrink_to_fit();
Copy link
Contributor

Choose a reason for hiding this comment

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

не совсем корректно, достаточно вызвать clear() обычно clear не меняет размер контейнера а просто передвигает укзаатель конца на начало и позволяет снова записывать элементы, в общем функция должна работать за O(1)

}
else {
SwapVecs(other.stack, stack, min_size);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

просто надо воспользоваться стандартным swap для вектора

size_t d2first = static_cast<size_t>(buf.m_first_ind - buf.m_buffer.begin());
m_first_ind = m_buffer.begin() + d2first;
m_last_ind = m_buffer.begin() + d2last;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

сложно, можно было все сделать в списках инициализации

int& RingBuffer::operator[](const size_t& ind) {
if (m_size == 0 || ind >= m_size || ind >= m_buffer.size()) {
int* n = nullptr;
return *n;
Copy link
Contributor

Choose a reason for hiding this comment

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

разыменование nullptr это UB

Copy link
Author

Choose a reason for hiding this comment

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

Вызов Front и Back от пустой очереди не ограничивается и ведет к UB. Так написано в ТЗ

if (m_size < m_buffer.capacity()) {
if (m_last_ind + 1 == m_buffer.end()) {
if (m_buffer.size() != m_buffer.capacity()) {
m_buffer.push_back(num);
Copy link
Contributor

Choose a reason for hiding this comment

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

слишком большая вложенность неудобно читать

++m_first_ind;
if (m_first_ind == m_buffer.end()) m_first_ind = m_buffer.begin();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

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


bool RingBuffer::TryPush(const int& num) {
if (m_size == m_buffer.capacity()) return false;
this->Push(num);
Copy link
Contributor

Choose a reason for hiding this comment

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

this-> не используется внутри класса

return true;
}

void RingBuffer::Resize(int new_capacity) {
Copy link
Contributor

Choose a reason for hiding this comment

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

надо принимать size_t

res.push_back(*(it + i));
}
return res;
} No newline at end of file
Copy link
Contributor

Choose a reason for hiding this comment

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

не понравилась реализация, можно было проще и лучше

Copy link
Contributor

@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.

@vova22013 нужно много поработать над написанием кода:

  • много лишних static_cast
  • лишние переменные в функциях
  • лишние тернарные операторы возвращающие true false
  • UB const_cast
  • некорректные сигнатуры функций
  • много дублирования и лишнего в коде
  • неоптимальные функции
  • лишнее копирвоание при сравнение Queue
  • использование this-> внутри класса
  • лишний код
  • не использование стандартных готовых функций
  • не понравилась реализация 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