Created
April 25, 2015 16:15
-
-
Save gofer/c131117cd771b2ede3d2 to your computer and use it in GitHub Desktop.
Vector2DBase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sstream> | |
#include <cmath> | |
template<typename T> | |
struct Vector2DBase | |
{ | |
T x, y; | |
Vector2DBase() : x(0.0), y(0.0) {} | |
Vector2DBase(T x, T y) : x(x), y(y) {} | |
Vector2DBase(const Vector2DBase& v) : x(v.x), y(v.y) {} | |
Vector2DBase operator+(const Vector2DBase& v) const | |
{ return Vector2DBase(x+v.x, y+v.y); } | |
Vector2DBase operator-(const Vector2DBase& v) const | |
{ return Vector2DBase(x-v.x, y-v.y); } | |
Vector2DBase operator*(T p) const | |
{ return Vector2DBase(x*p, y*p); } | |
Vector2DBase operator/(T p) const | |
{ return Vector2DBase(x/p, y/p); } | |
T operator*(const Vector2DBase& v) const | |
{ return x*v.x+y*v.y; } | |
Vector2DBase& operator+=(const Vector2DBase& v) | |
{ x+=v.x; y+=v.y; return *this; } | |
Vector2DBase& operator-=(const Vector2DBase& v) | |
{ x-=v.x; y-=v.y; return *this; } | |
Vector2DBase& operator*=(T p) | |
{ x*=p; y*=p; return *this; } | |
Vector2DBase& operator/=(T p) | |
{ x/=p; y/=p; return *this; } | |
Vector2DBase rotate(T t) | |
{ | |
return Vector2DBase( | |
x * ::cos(t) - y * ::sin(t), | |
x * ::sin(t) + y * ::cos(t) | |
); | |
} | |
T norm() const { return ::sqrt(x * x + y * y); } | |
Vector2DBase normalize() const | |
{ | |
double p = norm(); | |
return Vector2DBase(x/p, y/p); | |
} | |
std::string to_string() const | |
{ | |
std::stringstream ss; | |
ss << "(" << x << ", " << y << ")"; | |
return ss.str(); | |
} | |
}; | |
typedef Vector2DBase<double> Vector2D; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment