one-file-projects/vectors.cpp

95 lines
1.8 KiB
C++

#include <iostream>
template<unsigned int NDim, typename TElem>
class Vector {
private:
TElem coord[NDim];
public:
Vector() {}
Vector(const TElem initial) {
for(unsigned int i = 0; i < NDim; i++) {
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) {
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<DIM,int> 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;
}