mike.dl mike.dl - 1 year ago 89
C++ Question

divide STL vector by a scalar operator overload

I'm trying to overload the division operator to be able to divide an std::vector by a double scalar with the following:

template <typename T>
std::vector<T> operator/(const double& a, const std::vector<T>& b) {
std::vector<T> c(b.size());
for(int i=0;i<b.size();++i)
c[i] = b[i] / a;
return c;

If I then try to compute:

std::vector<double> M(Z.size());
M = Z / a;

where Z is a valid std::vector.

The compiler (Xcode) stops me saying "Invalid operands to invalid expression ('std::vector' and 'double'). Can anyone tell me why my template does not work and recommend me a suitable alternative, please?

Thanks very much!

Answer Source

Operator overload declarations in C++ are sensitive to argument order. Putting the vector first in the argument list would be more conventional.

Try either

std::vector<T> operator/(const std::vector<T>& b, const double& a)


M = a / Z;

Having said that, I agree with the comment from @krzaq that you really may benefit from looking at std::valarray and not reinventing the wheel. If you're goal is try learn more about templates and operator overloads, or if you have another goal in mind, knock yourself out.