矢量的平方根和平方在C++中加倍

Waw*_*100 0 c++ stl vector exponent square-root

我想计算双精度矢量的平方和平方根.例如给出:

 vector<double> Array1(10,2.0); 
 vector<double> Array2(10,2.0); 

 for(unsigned int i=0; i<Array1.size(); i++)
     Array1[i] = sqrt(Array1[i]);

 for(unsigned int i=0; i<Array2.size(); i++)
     Array2[i] = Array2[i] * Array2[i]; 
Run Code Online (Sandbox Code Playgroud)

有没有办法使用STL函数,如变换?也许有一个内置的sqrt函数作用于数组?

ken*_*ytm 7

上一个问题相同的答案......

static inline double computeSquare (double x) { return x*x; }

...

std::transform(Array1.begin(), Array1.end(), Array1.begin(), (double(*)(double)) sqrt);
std::transform(Array2.begin(), Array2.end(), Array2.begin(), computeSquare);
Run Code Online (Sandbox Code Playgroud)

((double(*)(double))强制转换是强制sqrt函数使用double变量 - 它是一个重载函数.你可以std::ptr_fun<double, double>(sqrt)用来避免强制转换.)