I have my own mathematical Vector class that I use in my code. I have a new need to generalize my vector class to n dimensions instead of just two.
My question is, what’s the best way to implement the operator overloads, and is there a significant overhead to doing this?
I now store the values in an array
double *vals;
....
vals = new double[dimension];
With this, I implement the + operator like so:
Vector Vector::operator+(Vector v)
{
Vector ret = Vector(dimension);
for (int i = 0; i < dimension; i ++)
{
ret.vals[i] = vals[i] + v.vals[i];
}
}
This operation will be done a LOT and has to run fast. Is this significantly worse than the old version (as far as speed)?
Vector Vector::operator+(Vector v) {
return Vector(x + v.x, y + v.y);
}
Thanks for any input!
If you want a fast vector class then use templates for the size:
Having them be dynamic size is only unnecessary if you want to re-size them, or if they are incredibly large.
There are ways to get much faster than this, such as SSE. You should use a dedicated math library if you want something highly optimized.