C++ Spaß mit Vektoren
This commit is contained in:
parent
9975af94f4
commit
5e9c0e47ac
1 changed files with 95 additions and 0 deletions
95
vectors.cpp
Normal file
95
vectors.cpp
Normal file
|
@ -0,0 +1,95 @@
|
|||
#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;
|
||||
}
|
Loading…
Reference in a new issue