Computational Physics - Department of Physics

(Axel Boer) #1

84 3 Numerical differentiation and interpolation


Vector& Vector::operator=(constVector& w){// v = w
if(this!= &w){ // beware of self-assignment v=v
if(length != w.length)
std::cout <<"Bad vector sizes"<< std::endl;
for(inti=0; i<length; i++)
vec[i] = w[i]; // closer to the mathematical notation than w.vec[i]
}
return*this;
}// assignment operator


Vector& Vector::operator+=(constVector& w){// v += w
if(length != w.length) std::cout <<"Bad vector sizes"<< std::endl;
for(inti=0; i<length; i++)
vec[i] += w[i];// This is possible because we have overloaded the operator[]
return*this;
}// add a vector to the current one


Vector& Vector::operator-=(constVector& w){// v -= w
if(length != w.length) std::cout <<"Bad vector sizes"<< std::endl;
for(inti=0; i<length; i++)
vec[i] -= w[i];// This possible because we have overloaded the operator[]
return*this;
}


Vector& Vector::operator=(doublescalar){// v= a
for(inti=0; i<length; i++)
vec[i]= scalar;
return
this;
}


Vector& Vector::operator/=(doublescalar){// v /= a
for(inti=0; i<length; i++)
vec[i] /= scalar;
return*this;
}


/**/
/ (Arithmetic) Binary operators /
/**/


// Sum of two vectors
Vectoroperator+(constVector& v,constVector& w){// u = v + w
// The copy constructor checks the lengths
returnVector(v) += w;
}// vector plus vector


// Substraction of two vectors
Vectoroperator-(constVector& v,constVector& w){// u = v - w
// The copy constructor checks the lengths
returnVector(v) -= w;
}// vector minus vector


// Multiplication between two vectors
Vectoroperator(constVector& v,constVector& w){// u = vw
if(v.length != w.length) std::cout <<"Bad vector sizes!"<< std::endl;
intn = v.length;
Vector tmp(n);
for(inti=0; i<n; i++)
tmp[i] = v[i]*w[i];
returntmp;
}// vector times vector

Free download pdf