HLPL2/Sem2/task1.cpp

128 lines
3.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
for (uint i = 0; i < size; i++) {
arr[i] = rand() % 100;
}
}
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;
}