向量数量是同时具有大小和方向的数量。在这里,数量级只是数量的数量或大小,方向是数量的前进方向。例如,考虑语句“向北20英里”。在上面的陈述中,20是震级,而North是方向。
例子:
Input : Store and display vector with components 3, 4, 5.
Output : 3i + 4j + 5k
Input : Dot Product for V1 = (1, 3, 5), V2 = (2, 3, 0)
Output : 11
where i, j, k are unit vectors in x, y and z directions respectively.
通常,向量表示为:
V = Xi + Yj + Zk
Where, X, Y and Z are the magnitude of the vector V in the directions i , j and k respectively.
可以在Vector上执行的各种操作:
- 向量的相加:向量的相加是通过将两个向量的相应X,Y和Z量值相加而得到的。
例子:
v1 = 1i + 2j + 3k
v2 = 3i + 2j + 1k
因此,结果向量v = v1 + v2 = 4i + 4j + 4k - 向量的点积:两个向量v1和v2的点积计算如下:
v = v1 . v2 = magnitude(v1)*magnitude(v2)*Cos(θ) Where, θ is the angle between the vectors v1 and v2.
例子:
v1 = 1i + 2j + 3k
v2 = 3i + 2j + 1k
因此,v = v1。 v2 = 3 + 4 + 3 = 10 - 向量的叉积:向量的叉积是通过使用行列式为向量A = AXI + AYJ + AZK且b = BXI + BYJ + BZK完成
c = a X b = i(ay * bz – by * az)– j(ax * bz – az * bx)+ k(ax * by – bx * ay)
例子:
v1 = 3i + 4j + 2k
v2 = 6i + 3j + 9k
因此,v = v1 X v2 = 30i – 15j – 15k
下面是在C++中使用类的上述操作的实现:
#include
#include
using namespace std;
class Vector {
private:
int x, y, z;
// Components of the Vector
public:
Vector(int x, int y, int z)
{
// Constructor
this->x = x;
this->y = y;
this->z = z;
}
Vector operator+(Vector v); // ADD 2 Vectors
Vector operator-(Vector v); // Subtraction
int operator^(Vector v); // Dot Product
Vector operator*(Vector v); // Cross Product
float magnitude()
{
return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
}
friend ostream& operator<<(ostream& out, const Vector& v);
// To output the Vector
};
// Addition of vectors
Vector Vector::operator+(Vector v)
{
int x1, y1, z1;
x1 = x + v.x;
y1 = y + v.y;
z1 = z + v.z;
return Vector(x1, y1, z1);
}
// Subtraction of vectors
Vector Vector::operator-(Vector v)
{
int x1, y1, z1;
x1 = x - v.x;
y1 = y - v.y;
z1 = z - v.z;
return Vector(x1, y1, z1);
}
// Dot product of vectors
int Vector::operator^(Vector v)
{
int x1, y1, z1;
x1 = x * v.x;
y1 = y * v.y;
z1 = z * v.z;
return (x1 + y1 + z1);
}
// Cross product of vectors
Vector Vector::operator*(Vector v)
{
int x1, y1, z1;
x1 = y * v.z - z * v.y;
y1 = z * v.x - x * v.z;
z1 = x * v.y - y * v.x;
return Vector(x1, y1, z1);
}
// Display Vector
ostream& operator<<(ostream& out, const Vector& v)
{
out << v.x << "i ";
if (v.y >= 0)
out << "+ ";
out << v.y << "j ";
if (v.z >= 0)
out << "+ ";
out << v.z << "k" << endl;
return out;
}
// Driver program
int main()
{
// Let us Take the vector quantites :
// V1 = 3i + 4j + 2k
// V2 = 6i + 3j + 9k
Vector V1(3, 4, 2), V2(6, 3, 9);
cout << "V1 = " << V1;
cout << "V2 = " << V2;
cout << "V1 + V2 = " << (V1 + V2);
cout << "Dot Product is : " << (V1 ^ V2);
cout << "Cross Product is : " << (V1 * V2);
return 0;
}
输出:
V1 = 3i + 4j + 2k
V2 = 6i + 3j + 9k
V1 + V2 = 9i + 7j + 11k
Dot Product is : 48Cross Product is : 30i -15j -15k
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。