执行向量操作 [英] Perform vector operation

查看:168
本文介绍了执行向量操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用向量容器来存储双精度数组。有没有任何快速
方式乘以一个标量的我的向量中的每个元素,而不使用循环。

I'm using the vector container to store an array of doubles. Is there any quick way of multiplying each element in my vector by some scalar without using a loop.

例如:

  vector<double> Array(10,1);

将用初始值1初始化10个双精度数组。要将此
数组乘以0.5我会写:

will initialise an array of 10 doubles with initial value 1. To multiply this array by 0.5 I would write:

  for(unsigned int i=0; i<Array.size(); i++) 
     Array[i] = 0.5*Array[i]; 

有另一种方法吗?我使用valarray重载'*'操作符
,以便:

Is there there another way? I have used valarray which overloads the '*' operator so that:

     Array = 0.5 * Array; 

是有效的,但我不想使用valarray,因为它似乎矢量容器是一个更多的
操作数组的标准方法。

is valid but I'd rather not use valarray as it seems the vector container is a more standard approach for manipulating arrays.

谢谢!

推荐答案

您可以这样做:

std::transform(Array.begin(), Array.end(), Array.begin(),
                std::bind2nd(std::multiplies<double>(), 0.5));

响应获取元素的总和:

double sum = std::accumulate(Array.begin(), Array.end(), 0.0);

并且为了获得 sqrt 每个元素:

And in response to getting sqrt'ing each element:

std::transform(Array.begin(), Array.end(), Array.begin(),
                static_cast<double (*)(double)>(std::sqrt));

这是要选择正确的重载。

That cast is to select the correct overload.

这篇关于执行向量操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆