1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <initializer_list>
#include <algorithm>
#include <iostream>
class Vector {
double* arr {};
size_t size {};
public:
friend Vector operator*(double scalar, const Vector& v);
friend Vector operator*(const Vector& v, double scalar);
friend std::ostream& operator<<(std::ostream& os, const Vector& v);
Vector(double* values, size_t siz) : arr(values), size(siz) {}
Vector(const std::initializer_list<double>& il) : size(il.size()), arr(new double[il.size()] {}) {
std::copy(il.begin(), il.end(), arr);
}
Vector(const Vector&) = delete;
Vector& operator=(const Vector&) = delete;
~Vector() { delete[] arr; }
};
std::ostream& operator<<(std::ostream& os, const Vector& v) {
for (size_t i = 0 ; i < v.size; ++i)
os << v.arr[i] << ' ';
return os << '\n';
}
//Multiplies the Vector by a scalar
Vector operator*(double scalar, const Vector& v) {
auto newArr {new double[v.size]};
for (size_t i = 0; i < v.size; ++i)
newArr[i] = scalar * v.arr[i];
return Vector(newArr, v.size);
}
Vector operator*(const Vector& v, double scalar) { return scalar * v; }
int main() {
const auto exampleVector {Vector{1.0, 2.0, 3.0}};
const auto resultVector {exampleVector * 4.0};
std::cout << resultVector << '\n';
}
|