templates/geometry-points.cpp
compilable
$cat templates/geometry-points
Geometry Points
Generic 2D point with full operator support: dot, cross, distance, rotation, unit, normal.
#geometry#point#vector#2d#cross-product
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
template <typename T = ll>
struct Point {
T x, y;
Point(T x = 0, T y = 0) : x(x), y(y) {}
Point operator+(const Point &p) const { return {x + p.x, y + p.y}; }
Point operator-(const Point &p) const { return {x - p.x, y - p.y}; }
Point operator*(T c) const { return {x * c, y * c}; }
Point operator/(T c) const { return {x / c, y / c}; }
bool operator==(const Point &p) const { return x == p.x && y == p.y; }
bool operator<(const Point &p) const { return tie(y, x) < tie(p.y, p.x); }
T dot(const Point &p) const { return x * p.x + y * p.y; }
T cross(const Point &p) const { return x * p.y - y * p.x; }
T cross(const Point &a, const Point &b) const { return (a - *this).cross(b - *this); }
T dist() const { return x * x + y * y; }
T dist(const Point &p) const { return (*this - p).dist(); }
ld distance() const { return sqrtl((ld)dist()); }
ld distance(const Point &p) const { return sqrtl((ld)dist(p)); }
ld angle() const { return atan2l((ld)y, (ld)x); }
ld angle(const Point &p) const { return atan2l((ld)cross(p), (ld)dot(p)); }
Point perp() const { return {-y, x}; }
Point unit() const { T d = dist(); return d ? *this / d : Point(); }
Point normal() const { return perp().unit(); }
Point rotate(ld a) const {
return Point(x * cosl(a) - y * sinl(a), x * sinl(a) + y * cosl(a));
}
Point rotate(const Point &p, ld a) const { return (*this - p).rotate(a) + p; }
friend istream &operator>>(istream &in, Point &p) { return in >> p.x >> p.y; }
friend ostream &operator<<(ostream &out, const Point &p) { return out << p.x << ' ' << p.y; }
};42 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
2D Point Template
A reusable generic point struct with arithmetic, geometric operations, and I/O.
Operations
+, -, *, / for vector mathp.cross(a, b) = cross product of vectors and long double)atan2l. angle(p) — signed angle between *this and pWhen to Use
T lets you switch between int, ll, double, long doubleNotes
dist() returns squared distance to avoid floating-point — use for integer comparisonsdistance() only when you need the actual Euclidean length