diff --git a/vectors.cpp b/vectors.cpp new file mode 100644 index 0000000..f5ce71e --- /dev/null +++ b/vectors.cpp @@ -0,0 +1,95 @@ +#include + +template +class Vector { +private: + TElem coord[NDim]; +public: + Vector() {} + + Vector(const TElem initial) { + for(unsigned int i = 0; i < NDim; i++) { + coord[i] = initial; + } + } + + Vector + operator+ (const Vector& other) + { + Vector result; + for(unsigned int i = 0; i < NDim; i++) { + result[i] = this->coord[i] + other[i]; + } + return result; + } + + Vector + operator+= (const Vector& other) + { + for(unsigned int i = 0; i < NDim; i++) { + this->coord[i] += other[i]; + } + return *this; + } + + Vector + operator- () + { + Vector result; + for(unsigned int i = 0; i < NDim; i++) + { + result[i] = -this->coord[i]; + } + return result; + } + + Vector + operator*(TElem factor) + { + Vector 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 +void printVector(const Vector v) { + printf("%d", v[0]); + for(int i = 1; i < NDim; i++) { + printf(", %3d", v[i]); + } + printf("\n"); +} + +#define DIM 3 + +int main( int argc, char *argv[] ) { + Vector a(0),b(0),c(0),d(0); + for(int i = 0; i < DIM; i++) { + a[i] = 10*i; + b[i] = 5-i; + } + + printVector(a); + printVector(b); + + c = a + b; + + printVector(c); + + d = a*3 + c*4; + + printVector(d); + + return 0; +}