Last active
December 29, 2015 09:09
-
-
Save PatrickLerner/7647889 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Patrick Lerner | |
* Manual Spari | |
*/ | |
#include <iostream> | |
#include <cmath> | |
template <typename T, int N> | |
class Vector | |
{ | |
private: | |
T *data; | |
public: | |
Vector() { | |
this->data = new T[N]; | |
}; | |
T& operator[](int index) { | |
return data[index]; | |
}; | |
Vector<T, N> operator+(Vector<T, N> &otherOne) { | |
Vector<T, N> result; | |
for (int i = 0; i < N; i++) | |
result[i] = data[i] + otherOne[i]; | |
return result; | |
}; | |
Vector<T, N> operator*(float otherOne) { | |
Vector<T, N> result; | |
// scalar multiplication | |
for (int i = 0; i < N; i++) | |
result[i] = data[i] * otherOne; | |
return result; | |
}; | |
T operator*(Vector<T, N> &otherOne) { | |
T sum = 0; | |
// scalar product | |
for (int i = 0; i < N; i++) | |
sum += data[i] * otherOne[i]; | |
return sum; | |
}; | |
void print() { | |
for (int i = 0; i < N; i++) | |
std::cout << data[i] << (i < N-1 ? "\t" : "\n"); | |
}; | |
float length() { | |
// length is squareroot of the sum of | |
// all the squares of the entries | |
float powersum = 0; | |
for (int i = 0; i < N; i++) | |
powersum += pow(data[i], 2); | |
return sqrt(powersum); | |
}; | |
}; | |
int main() | |
{ | |
typedef Vector<float, 3> Vector; | |
Vector f, g; | |
f[0] = 1.0f; f[1] = 2.0f; f[2] = 3.0f; | |
g[0] = 3.0f; g[1] = 2.0f; g[2] = 1.0f; | |
Vector h = f + g; | |
Vector m = g * 3.0f; | |
f.print(); // 1 2 3 | |
g.print(); // 3 2 1 | |
h.print(); // 4 4 4 | |
m.print(); // 9 6 3 | |
std::cout << (f * g) << '\n' // 10 | |
<< f.length() << std::endl; // 3.74166 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment