Skip to content

Osadchyi homework3#43

Open
NikOsadchyi wants to merge 6 commits intomainfrom
OsadchyiHomework3
Open

Osadchyi homework3#43
NikOsadchyi wants to merge 6 commits intomainfrom
OsadchyiHomework3

Conversation

@NikOsadchyi
Copy link
Collaborator

No description provided.

Copy link
Collaborator

@GKuzzinshtern GKuzzinshtern left a comment

Choose a reason for hiding this comment

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

В общем, там где мои мысли повторялись, я их уже не писал.
Хочу отметить, что нежелательно использовать имена переменных типа i,j,k даже если на данный момент это однозначный маленький цикл. Он со временем может наполнится еще кодом и читатели будут гадать что означает эта буква. Короткое содержательное имя - будет самое то! :)

homework3.cpp Outdated
}

bool is_dgt(char var) {
int dec_v = static_cast<int>(var);
Copy link
Collaborator

Choose a reason for hiding this comment

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

можно пользоваться операторами сравнения для char. Не стоит их кастить в данном случае к int

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

сравнивать что символ является числом? 10 сравнений?)

Copy link
Collaborator

Choose a reason for hiding this comment

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

if (var >= '0' && var <= '9') - начить это цифра

homework3.cpp Outdated
}

void reverse_str() {
constexpr int arr_len{100};
Copy link
Collaborator

Choose a reason for hiding this comment

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

для размеров можно использовать size_t вместо int

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

это наверное дело вкуса?)

Copy link
Collaborator

Choose a reason for hiding this comment

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

сам не могу привыкнуть :(

homework3.cpp Outdated
int arr[arr_len]{};
for (int i = 0; i < arr_len; ++i) {
int val{};
std::cout << "Enter a number: ";
Copy link
Collaborator

Choose a reason for hiding this comment

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

побольше тексту!

homework3.cpp Outdated
std::cin >> val;
for (int j = 0; j < arr_len; ++j) {
std::cout << val;
if (arr[j] == 0) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

если пользователь введет "0", похоже будет "ой" :( Практика использовать потенциально возможное значение как критерий поведения к хорошему не приводит. Т.е. 0 - не должен означать, что ячейка не заполнена.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

согласен, пока что не придумал решения. Заводить флаг, если первый элемент, то ставить его первым, а дальше от него шагать?

Copy link
Collaborator

Choose a reason for hiding this comment

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

или смещать элементы на место удаленного...

homework3.cpp Outdated
for (int j = 0; j < arr_len; j++) {
if (num == arr[j]) {
std::cout << "Element " << num << " is removed from array" << std::endl;
arr[j] = '-';
Copy link
Collaborator

Choose a reason for hiding this comment

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

не-не-не. Так нельзя делать. У Вас arr - это интовый массив. То что Вы присвоили, компилятор неявно преобразовал const char в int. И значение в данный элемент массива попало 45. Если бы Вы вывели итоговый массив, то увидели бы это.
Здесь вообще, по-моему, надо поступать аналогично с заданием на добавление числа. Только при удалении смещать элементы массива, чтоб заполнить освободившееся место.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

придумал обходной костыль.)

Copy link
Collaborator

Choose a reason for hiding this comment

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

Зачем? Смещайте элементы. std::string здесь вообще не к месту (хоть я его и люблю :) )

Repository owner deleted a comment Dec 3, 2020
#include <locale>

int get_str_len(char* str) {
int count{};
Copy link
Owner

Choose a reason for hiding this comment

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

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

Comment on lines +19 to +22
int str_len = get_str_len(_str);

int strt = 0;
int end = str_len - 1;
Copy link
Owner

Choose a reason for hiding this comment

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

Suggested change
int str_len = get_str_len(_str);
int strt = 0;
int end = str_len - 1;
int str_len {get_str_len(_str)};
int strt {0};
int end {str_len - 1};

bool is_dgt(char var) {
int dec_v = static_cast<int>(var);
constexpr int lwr_ascii_dec_lim = 48;
constexpr int uppr_ascii_dec_lim = 57;
Copy link
Owner

Choose a reason for hiding this comment

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

как вы думаете тот кто читает этот код он знает на изусть таблицу ascii?)
лучше писать символьные литералы 0

arr[i] = arr[i] & '_';
}
else {
arr[i] = arr[i];
Copy link
Owner

Choose a reason for hiding this comment

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

а зачем это? просто не надо else ветки

std::cin >> arr;
for (int i = 0; arr[i] != '\0'; ++i) {
if (std::isalpha(arr[i], loc)) {
arr[i] = arr[i] & '_';
Copy link
Owner

Choose a reason for hiding this comment

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

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


void remove_elmtn() {
constexpr int arr_len{ 5 };
std::string arr[arr_len];
Copy link
Owner

Choose a reason for hiding this comment

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

ничего не понял а зачем вам массив строк?


while (elmnts_deleted != arr_len) {
bool present = false;
std::string num{};
Copy link
Owner

Choose a reason for hiding this comment

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

зачем тут string в качестве строки?

std::string num{};
std::cout << "Enter a number which you want to delete from array: ";
std::cin >> num;
std::string rmvd_ch = "-";
Copy link
Owner

Choose a reason for hiding this comment

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

непонял вообще что это и зачем эта магия?
просто проверяйте что строка не пустая и все я думаю что этого вполне достаточно

std::cin >> num;
std::string rmvd_ch = "-";
for (int j = 0; j < arr_len; j++) {
if (num == arr[j] && arr[j] != rmvd_ch) {
Copy link
Owner

Choose a reason for hiding this comment

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

вот подумайте над этим условием. что куда лучше поставить, т.е. поменять местами

arr[j] = val;
val = tmp;
j = 0;
}
Copy link
Owner

Choose a reason for hiding this comment

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

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

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.

3 participants

Comments