Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion homework_01/task_01/src/main.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#include <iostream>

#include <utils.hpp>
#include "utils.hpp"

int main() {
for (const auto& word : SplitString("asdas das das fgag (adasd 1fas)")) {
Expand Down
3 changes: 2 additions & 1 deletion homework_01/task_01/src/split_string_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ TEST_CASE("SplitString", "[simple]") {
CHECK(SplitString("??? ??") == std::vector<std::string>{"???", "??"});
CHECK(SplitString("a\na\ta a") == std::vector<std::string>{"a\na", "a", "a"});
CHECK(SplitString("a (a a)") == std::vector<std::string>{"a", "(a a)"});
CHECK(SplitString("a (a a) b (asd as) ") == std::vector<std::string>{"a", "(a a)", "b", "(asd as)"});
CHECK(SplitString("a (a a) b (asd as) ") ==
std::vector<std::string>{"a", "(a a)", "b", "(asd as)"});
}
37 changes: 33 additions & 4 deletions homework_01/task_01/src/utils.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,36 @@
#include "utils.hpp"

#include <stack>
#include <string>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В первую строку принято помещать включение одноимённого хидера #include "utils.hpp". Остальные инклюды идут после и отделяются от одноимённого хидела пустой строкой

#include <string_view>
#include <vector>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Между инклюдами и первой строчкой кода принято размещать пустую строку (так у текста в файле появляется структура)


std::vector<std::string> SplitString(const std::string& data) {
return {};
}
std::vector<std::string> SplitString(std::string const& data) {
std::vector<std::string> result;
std::string token = "";
bool brackets_condition = false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вас можно похвалить за выбор говорящих имён для переменных. Но над именами можно ещё подумать. Например, final_array лечше, чем finish_array, а ещё лучше result или res. active_data я бы переназвал как word или token

for (char const& active_element : data) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вместо имени active_element можно просто ch или даже c. Если хотите избегать коротких имён, то больше подходит имя current_char

А ещё значение элементарного типа тут лучше просто копировать, чем брать по ссылке: for (const char active_element : data) {

if (brackets_condition) {
token.push_back(active_element);
if (active_element == ')') {
brackets_condition = false;
result.push_back(token);
token = "";
}
} else {
if (active_element == ' ' || active_element == '\t') {
if (!token.empty()) {
result.push_back(token);
token = "";
}
} else {
active_data.push_back(active_element);
if (active_element == '(') brackets_condition = true;
}
}
}
if (!token.empty()) {
result.push_back(active_data);
token = "";
}
return result;
};
2 changes: 1 addition & 1 deletion homework_01/task_01/src/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
#include <string_view>
#include <vector>

std::vector<std::string> SplitString(const std::string& data);
std::vector<std::string> SplitString(const std::string& data);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В конец файла принято добавлять пустую строку

11 changes: 9 additions & 2 deletions homework_01/task_02/src/calculate_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#include "utils.hpp"

TEST_CASE("Calculate", "[simple_sum]") {
CHECK(Calculate("1+2") == 3);
CHECK(Calculate("12+2") == 14);
CHECK(Calculate("2+2") == 4);
CHECK(Calculate("1+0") == 1);
CHECK(Calculate("0+0") == 0);
Expand All @@ -17,8 +17,15 @@ TEST_CASE("Calculate", "[simple_difference]") {
}

TEST_CASE("Calculate", "[simple_multiply]") {
CHECK(Calculate("5*2") == 10);
CHECK(Calculate("52*2") == 104);
CHECK(Calculate("2*2") == 4);
CHECK(Calculate("1*0") == 0);
CHECK(Calculate("0*0") == 0);
}

TEST_CASE("Calculate", "[simple_del]") {
CHECK(Calculate("52/2") == 26);
CHECK(Calculate("2/2") == 1);
CHECK(Calculate("0/3") == 0);
CHECK(Calculate("23/1") == 23);
}
1 change: 0 additions & 1 deletion homework_01/task_02/src/main.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#include <iostream>

#include <utils.hpp>

int main() {
Expand Down
38 changes: 35 additions & 3 deletions homework_01/task_02/src/utils.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
#include "utils.hpp"

#include <cstring>
#include <iostream>
#include <stack>

int Calculate(const std::string& data) {
return 0;
}
int Calculate(const std::string &data) {
std::string number = "";
char action;
int variables[2];
int answer = 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Имена переменных очень неудачные, за исключением, пожалуй, action и answer, да и то math_operator и result мне кажутся лучшими альтернативами.

Чтобы не мучиться подбором подходящего имени, иногда можно просто сократить число переменных. Я бы из 6-ти переменных оставил максимум четыре:

std::string number_part;
char math_operator;
std::vector<int> numbers;
int result;


for (char c : data) {
if (c >= '0' && c <= '9') {
number = number + c;
} else {
numbers.push_back(std::stoi(number_part)) number.clear();
if ((c == '+') || (c == '-') || (c == '*') || (c == '/')) {
action = c;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Кстати, на будущее замечу, что если во входной строке не окажется арифметического оператора, то переменная action останется вообще неинициализорованной, и обращение к ней приведёт к undefined behavior. Лучше в коде такого не допускать

}
}
}

int_numbers[n] = atoi(number.c_str());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

numbers.push_back(std::stoi(number_part));


if (action == '+') {
answer = (int_numbers[0] + int_numbers[1]);
}
if (action == '-') {
answer = (int_numbers[0] - int_numbers[1]);
}
if (action == '*') {
answer = (int_numbers[0] * int_numbers[1]);
}
if (action == '/') {
answer = (int_numbers[0] / int_numbers[1]);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вместо сцепленных if для целочисленных типов рекомендуется использовать оператор switch (но это вопрос вкуса/кодстайла)

return answer;
}