HLPL2/Sem3/task2.cpp
2020-10-05 08:16:28 +00:00

150 lines
3.6 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 <cmath>
#include <cstring>
#include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
class DynArr {
private:
T* arr;
uint size;
public:
void set(uint index, T value)
{
if (index < size) {
arr[index] = value;
} else {
throw out_of_range("Tried to set element out of array bounds!");
}
}
T get(uint index)
{
if (index < size) {
return arr[index];
}
throw out_of_range("Tried to get element out of array bounds!");
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";
}
void dynAdd(T value)
{
T* newArr = new T[size + 1];
memcpy(newArr, arr, sizeof(T) * size);
delete[] arr;
arr = newArr;
arr[size] = value;
size = size + 1;
}
DynArr operator<<(std::ostream& os)
{
for (uint i = 0; i < size; i++) {
os << arr[i] << " ";
}
}
inline bool operator<(const DynArr& rhs)
{
if (size == rhs.size) {
double lengthL = 0;
double lengthR = 0;
for (uint i = 0; i < size; i++) {
lengthL += arr[i] * arr[i];
lengthR += rhs.arr[i] * rhs.arr[i];
}
lengthL = sqrt(lengthL);
lengthR = sqrt(lengthR);
return lengthL < lengthR;
} else {
return size < rhs.size;
}
}
inline bool operator>(const DynArr& rhs) { return rhs < this; }
inline bool operator<=(const DynArr& rhs) { return !(this > rhs); }
inline bool operator>=(const DynArr& rhs) { return !(this < rhs); }
DynArr(uint dsize)
{
arr = new T[dsize];
size = dsize;
for (uint i = 0; i < size; i++) {
arr[i] = rand() % 100;
}
}
DynArr(const DynArr& original)
{
size = original.size;
arr = new T[original.size];
memcpy(arr, original.arr, sizeof(T) * size);
}
~DynArr()
{
delete[] arr;
}
};
int main()
{
int i, temp;
cout << "Введите размер первого массива: ";
cin >> i;
DynArr<int> 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<int> arr2(i);
i = 0;
while (i >= 0) {
try {
cout << "Введите номер элемента: ";
cin >> i;
if (i >= 0) {
cout << "Введите его значение: ";
cin >> temp;
arr2.set(i, temp);
}
} catch (const std::out_of_range& e) {
cerr << e.what() << endl;
} catch (const std::invalid_argument& e) {
cerr << "Invalid number" << endl;
}
}
cout << "Первый массив:\n";
arr.print();
cout << "Второй массив:\n";
arr2.print();
if (arr < arr2) {
cout << "Второй массив больше первого" << endl;
} else {
cout << "Первый массив больше второго" << endl;
}
return 0;
}