Refactoring of vectors

This commit is contained in:
madmaurice 2016-01-19 18:27:17 +01:00
parent 5e9c0e47ac
commit 5f72632917

View file

@ -1,95 +1,51 @@
#include <iostream> #include <iostream>
#include "vectors.hpp"
template<unsigned int NDim, typename TElem> /** A print function the Vector type
class Vector { *
private: * this function print a vector which contains integers
TElem coord[NDim]; *
public: * @tparam NDim dimension of the Vector
Vector() {} * @param v the vector to be printed
*/
Vector(const TElem initial) { template<
for(unsigned int i = 0; i < NDim; i++) { unsigned int NDim
coord[i] = initial; >
}
}
Vector<NDim, TElem>
operator+ (const Vector<NDim, TElem>& other)
{
Vector<NDim, TElem> result;
for(unsigned int i = 0; i < NDim; i++) {
result[i] = this->coord[i] + other[i];
}
return result;
}
Vector<NDim, TElem>
operator+= (const Vector<NDim, TElem>& other)
{
for(unsigned int i = 0; i < NDim; i++) {
this->coord[i] += other[i];
}
return *this;
}
Vector<NDim, TElem>
operator- ()
{
Vector<NDim, TElem> result;
for(unsigned int i = 0; i < NDim; i++)
{
result[i] = -this->coord[i];
}
return result;
}
Vector<NDim, TElem>
operator*(TElem factor)
{
Vector<NDim, TElem> result;
for(unsigned int i = 0; i < NDim; i++) {
result[i] = this->coord[i] * factor;
}
return result;
}
TElem& operator[](const unsigned int index) {
return this->coord[index];
}
const TElem operator[](const unsigned int index) const {
return this->coord[index];
}
};
template<unsigned int NDim>
void printVector(const Vector<NDim, int> v) { void printVector(const Vector<NDim, int> v) {
printf("%d", v[0]); printf("Vector [ %d", v[0]);
for(int i = 1; i < NDim; i++) { for(int i = 1; i < NDim; i++) {
printf(", %3d", v[i]); printf(", %d", v[i]);
} }
printf("\n"); printf(" ] length %d\n", v.length());
}
/** A print function the Vector type
*
* this function print a vector which contains floats
*
* @tparam NDim dimension of the Vector
* @param v the vector to be printed
*/
template<
unsigned int NDim
>
void printVector(const Vector<NDim, float> v) {
printf("Vector [ %.3f", v[0]);
for(int i = 1; i < NDim; i++) {
printf(", %.3f", v[i]);
}
printf(" ] length %.3f\n", v.length());
} }
#define DIM 3 #define DIM 3
int main( int argc, char *argv[] ) { int main( int argc, char *argv[] ) {
Vector<DIM,int> a(0),b(0),c(0),d(0); Vector<3,int> a{1,2,3};
for(int i = 0; i < DIM; i++) { Vector<3,float> c;
a[i] = 10*i;
b[i] = 5-i;
}
printVector(a);
printVector(b);
c = a + b;
c = a.normalize();
printVector(c); printVector(c);
d = a*3 + c*4; a = c;
printVector(a);
printVector(d);
return 0;
} }