Sem 2 task 1 done?

This commit is contained in:
Inex Code 2020-09-21 07:38:51 +00:00
parent bc0216c5f7
commit f7abaa6d9d
2 changed files with 130 additions and 0 deletions

8
Sem2/Makefile Normal file
View File

@ -0,0 +1,8 @@
CXX = g++
CXXFLAGS = -Wall -g --std=c++11
main: task1.o
task1.o: task1.cpp
clang-format -i --style=webkit task1.cpp
$(CXX) $(CXXFLAGS) -o task1.o task1.cpp

122
Sem2/task1.cpp Normal file
View File

@ -0,0 +1,122 @@
#include <cstring>
#include <iostream>
using namespace std;
class DynArr {
private:
int* arr;
uint size;
public:
void set(uint index, int value)
{
if (index < size) {
if (-100 <= value && value <= 100) {
arr[index] = value;
} else {
cerr << "Tried to set element " << index << " with " << value << " but this value is not in [-100; 100]";
}
} else {
cerr << "Tried to set element " << index << " with " << value << " but the array size is " << size << ". Skipping.\n";
}
}
int get(uint index)
{
if (index < size) {
return arr[index];
}
cerr << "Tried to get element " << index << " from an array with size " << size << ". Returning 0.\n";
return 0;
}
uint length()
{
return size;
}
void print()
{
cout << "Size is " << size << endl;
for (uint i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << "\n";
}
DynArr operator+ (const DynArr& second) {
DynArr result(second);
uint target_size = size;
if (second.size < size) target_size = second.size;
for (uint i = 0; i < target_size; i++) {
result.set(i, result.get(i) + arr[i]);
}
return result;
}
DynArr operator- (const DynArr& second) {
DynArr result(second);
uint target_size = size;
if (second.size < size) target_size = second.size;
for (uint i = 0; i < target_size; i++) {
result.set(i, arr[i] - result.get(i));
}
return result;
}
DynArr(uint dsize)
{
arr = new int(dsize);
size = dsize;
}
DynArr(const DynArr& original)
{
size = original.size;
arr = new int(original.size);
memcpy(arr, original.arr, sizeof(int) * size);
}
~DynArr()
{
delete[] arr;
}
};
int main()
{
int i, temp;
cout << "Введите размер первого массива: ";
cin >> i;
DynArr arr(i);
i = 0;
while (i >= 0) {
cout << "Введите номер элемента: ";
cin >> i;
if (i >= 0) {
cout << "Введите его значение: ";
cin >> temp;
arr.set(i, temp);
}
}
cout << "Первый массив:\n";
arr.print();
cout << "Введите размер второго массива: ";
cin >> i;
DynArr arr2(i);
i = 0;
while (i >= 0) {
cout << "Введите номер элемента: ";
cin >> i;
if (i >= 0) {
cout << "Введите его значение: ";
cin >> temp;
arr2.set(i, temp);
}
}
cout << "Первый массив:\n";
arr.print();
cout << "Второй массив:\n";
arr2.print();
cout << "Первый + второй:\n";
(arr + arr2).print();
cout << "Первый - второй:\n";
(arr - arr2).print();
return 0;
}