C++的STL中的vector是一个动态数组,可以表示多维向量(一般平面二维向量对应的vector的size为2,三维对应的size为3), 求向量v的笛卡尔长度则为v点乘v自己的开平方根。
#include <iostream>
#include <vector>
#include <math.h>
bool vetor_dot_mul(const std::vector<double>& a, const std::vector<double>& b, int n, double& res)
{
if (a.size() != n || b.size() != n)
{
return false;
}
res = 0.0;
for (int i = 0; i < n; i++)
{
double m = a[i] * b[i];
res += m;
}
}
double vector_length(const std::vector<double>& a)
{
double s = 0.0;
vetor_dot_mul(a, a, a.size(), s);
return sqrt(s);
}
int main()
{
std::vector<double> v0;
v0.push_back(1.0); //[1.0]
v0.push_back(1.2); //[1.0,1.2]
v0.push_back(1.3); //[1.0,1.2,1.3]
v0.push_back(1.4); //[1.0,1.2,1.3,1.4]
std::vector<double> v1 = {1.0,1.0,1.0,1.0};
double v4dotmul = 0.0;
vetor_dot_mul(v0, v1, 4, v4dotmul);
std::cout << "R(4) vector dot mul: a*b = " << v4dotmul << std::endl;
system("pause");
return 0;
}