模板 =========== 向量 ********** :: 封装了一下array,支持向量间的加减,标量乘除法,向量点乘以及3维向量的叉乘,重载了`<<`。 .. code:: cpp template struct Vector { std::array v; Vector() : v() {} Vector(const std::array &v) : v(v) {} Type &operator[](const int i) { return v[i]; } const Type &operator[](const int i) const { return v[i]; } Vector operator+(const Vector &other) const { Vector res; for (int i = 0; i < N; i++) res[i] = v[i] + other[i]; return res; } Vector &operator+=(const Vector &other) { for (int i = 0; i < N; i++) v[i] += other[i]; return *this; } Vector operator-() const { Vector res; for (int i = 0; i < N; i++) res[i] = -v[i]; return res; } Vector operator-(const Vector &other) const { Vector res; for (int i = 0; i < N; i++) res[i] = v[i] - other[i]; return res; } Vector &operator-=(const Vector &other) { for (int i = 0; i < N; i++) v[i] -= other[i]; return *this; } Type operator*(const Vector &other) const { Type res = 0; for (int i = 0; i < N; i++) res += v[i] * other[i]; return res; } Vector operator*(const Type &scalar) const { Vector res; for (int i = 0; i < N; i++) res[i] = v[i] * scalar; return res; } Vector &operator*=(const Type &scalar) { for (int i = 0; i < N; i++) v[i] *= scalar; return *this; } Vector operator/(const Type &scalar) const { Vector res; for (int i = 0; i < N; i++) res[i] = v[i] / scalar; return res; } Vector &operator/=(const Type &scalar) { for (int i = 0; i < N; i++) v[i] /= scalar; return *this; } Vector cross(const Vector &other) const { static_assert(N == 3, "Cross product is only defined for 3D vectors."); Vector res; res[0] = v[1] * other[2] - v[2] * other[1]; res[1] = v[2] * other[0] - v[0] * other[2]; res[2] = v[0] * other[1] - v[1] * other[0]; return res; } Type magnitude() const { Type res = 0; for (int i = 0; i < N; i++) res += v[i] * v[i]; return std::sqrt(res); } Vector normalized() const { return (*this) * (1.f / magnitude()); } friend std::ostream &operator<<(std::ostream &os, const Vector &vector) { os << "("; for (int i = 0; i < N - 1; ++i) os << vector.v[i] << ", "; os << vector.v[N - 1] << ")"; return os; } }; using vec3 = Vector; int main() { Vector a({1, 2, 3}); vec3 b({4, 5, 6}); auto c = a + b; vec3 d = a - b; vec3 e = a * 2.0; vec3 f = a.cross(b); int dot = a * b; Vector g({0.1f, 0.2f, 0.3f}); std::cout << std::fixed << std::setprecision(3) << c << '\n' << d << '\n' << e << '\n' << f << '\n' << dot << '\n' << g << std::endl; return 0; }