-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoint.cpp
More file actions
76 lines (58 loc) · 1.57 KB
/
point.cpp
File metadata and controls
76 lines (58 loc) · 1.57 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// Pointer class implementation
//
#include "point.h"
#include <iostream>
using namespace std;
// Constructor
Point::Point(int dimen) {
// Could not accept dimension less then 2, don't return an error, but set default
if (dimen < 2)
dimen= 2;
coord.resize(dimen);
for (int i = 0; i < dimen; ++i)
coord[i] = 0.0;
} // Constructor
Point::Point(vector<double> p_coord)
{
coord = p_coord;
size_t dimen = coord.size();
if (dimen < 1)
{
coord.resize(2);
if (dimen == 0)
coord[0] = 0.0;
coord[1] = 0.0;
}
}
// Function to calculate distance to other point
double Point::dist(Point other) {
double sum = 0;
for (int i = 0; i < coord.size(); ++i)
sum += pow(coord[i] - other.coord[i], 2);
return sqrt(sum);
}
Point operator+ (Point& p1, Point& p2) {
int majorDim = (p1.coord.size() > p2.coord.size() ? p1.coord.size() : p2.coord.size());
Point sum(majorDim); // Create a variable coordinates 0s with greater dimension
for (int i=0; i < majorDim; i++) {
if ((i+1) <= p1.coord.size())
sum.coord[i] += p1.coord[i];
if ((i+1) <= p2.coord.size())
sum.coord[i] += p2.coord[i];
}
return sum;
}
Point operator* (double m1, Point& p1) {
Point prod(p1.coord.size()); // Create a variable coordinates 0s
for (int i=0; i < p1.coord.size(); i++)
prod.coord[i] = m1 * p1.coord[i];
return prod;
}
ostream& operator<< (ostream&out, Point& p) {
out << "(";
for (int i = 0; i < p.coord.size() - 1; ++i)
out << p.coord[i] << ", ";
out << p.coord[p.coord.size() - 1] << ")";
return out;
}