operator overloading - % operation for two vectors in C++ -
i have 2 vectors , b (with x
,y
& z
coordinates) , want know whether a % b
valid operation or not read somewhere /
operation not valid 2 vectors , since %
involves division hence confusion. if %
valid how can overload %
operator in c++
operation.
this vector class:
class vec { public: float x, y, z; };
it depends on mean "valid operation". there's no %
operation defined standard library std::vector
s, free define own operator overload that. it's not particularly idea - if every library decided operator use clash (i.e. ambiguous in contexts) - in practice you'll away it. more structured approach, consider creating own class sporting nifty operators, instead of modifying behaviour std::vector
.
the basics of overloading just:
template <typename t> std::vector<t> operator%(const std::vector<t>& lhs, const std::vector<t>& rhs) { // generate , return vector, example... std::vector<t> result; (size_t = 0; < std::min(lhs.size(), rhs.size()); ++i) result.push_back(rhs[i] ? lhs[i] % rhs[i] : 0); return result; }
update - given own vec
class (and assuming have c++11 compiler /- can search how enable c++11 features separately).
vec operator%(const vec& lhs, const vec& rhs) { return { lhs.x % rhs.x, lhs.y % rhs.y, lhs.z % rhs.z }; }
for c++03, either add constructor vec(float ax, float ay, float az) : x(ax), y(ay), z(az) { }
, in ther operator return vec(lhs.x % rhs.x, lhs.y % rhs.y, lhs.z % rhs.z);
or - without constructor...
vec result; result.x = lhs.x % rhs.x; result.y = lhs.y % rhs.y; result.z = lhs.z % rhs.z; return result;
of course, above implementations assume want use mod on correspondingly indexed elements... have no idea makes sense in problem domain.
Comments
Post a Comment