[英]Multiply vector elements by a scalar value using STL
Hi I want to (multiply,add,etc) vector by scalar value for example myv1 * 3
, I know I can do a function with a forloop , but is there a way of doing this using STL function?嗨,我想(乘、加等)向量按标量值,例如myv1 * 3
,我知道我可以用 forloop 做一个函数,但是有没有办法使用 STL 函数来做到这一点? Something like the {Algorithm.h :: transform function }? {Algorithm.h :: 变换函数}之类的东西?
Yes, using std::transform
:是的,使用std::transform
:
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind(std::multiplies<T>(), std::placeholders::_1, 3));
Before C++17 you could use std::bind1st()
, which was deprecated in C++11.在 C++17 之前,您可以使用在 C++11 中已弃用的std::bind1st()
。
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind1st(std::multiplies<T>(), 3));
For the placeholders;对于占位符;
#include <functional>
If you can use a valarray
instead of a vector
, it has builtin operators for doing a scalar multiplication.如果您可以使用valarray
而不是vector
,它具有用于执行标量乘法的内置运算符。
v *= 3;
If you have to use a vector
, you can indeed use transform
to do the job:如果您必须使用vector
,您确实可以使用transform
来完成这项工作:
transform(v.begin(), v.end(), v.begin(), _1 * 3);
(assuming you have something similar to Boost.Lambda that allows you to easily create anonymous function objects like _1 * 3
:-P) (假设您有类似于Boost.Lambda的东西,它允许您轻松创建匿名函数对象,例如_1 * 3
:-P)
Modern C++ solution for your question.您的问题的现代 C++ 解决方案。
#include <algorithm>
#include <vector>
std::vector<double> myarray;
double myconstant{3.3};
std::transform(myarray.begin(), myarray.end(), myarray.begin(), [&myconstant](auto& c){return c*myconstant;});
I think for_each
is very apt when you want to traverse a vector and manipulate each element according to some pattern, in this case a simple lambda would suffice:我认为当你想遍历一个向量并根据某种模式操作每个元素时, for_each
非常合适,在这种情况下,一个简单的 lambda 就足够了:
std::for_each(myv1.begin(), mtv1.end(), [](int &el){el *= 3; });
note that any variable you want to capture for the lambda function to use (say that you eg wanted to multiply with some predetermined scalar), goes into the bracket as a reference.请注意,您想要捕获以供 lambda 函数使用的任何变量(例如,您想要与某个预定的标量相乘),都会作为参考放入括号中。
If you had to store the results in a new vector , then you could use the std::transform()
from the <algorithm>
header:如果您必须将结果存储在一个新的 vector中,那么您可以使用<algorithm>
标头中的std::transform()
:
#include <algorithm>
#include <vector>
int main() {
const double scale = 2;
std::vector<double> vec_input{1, 2, 3};
std::vector<double> vec_output(3); // a vector of 3 elements, Initialized to zero
// ~~~
std::transform(vec_input.begin(), vec_input.end(), vec_output.begin(),
[&scale](double element) { return element *= scale; });
// ~~~
return 0;
}
So, what we are saying here is,所以,我们在这里要说的是,
element
s) of vec_input
starting from the beginning ( vec_input.begin()
) to the end ( vec_input.begin()
),取vec_input
从开头 ( vec_input.begin()
) 到结尾 ( vec_input.begin()
) 的值 ( element
s),
[beginning, end)
) to transform, range本质上,使用前两个参数,您指定要转换的元素范围( [beginning, end)
),范围element
to the last argument, lambda expression,将每个element
传递给最后一个参数 lambda 表达式,vec_output
starting from the beginning ( vec_output.begin()
).获取 lambda 表达式的输出并将其放入vec_output
从头开始( vec_output.begin()
)。
The lambda expression拉姆达表达式
[&scale]
) from outside by reference,通过引用从外部捕获比例因子 ( [&scale]
) 的值,std::transform()
)将 double 类型的向量元素作为输入(由std::transform()
传递给它)vec_input
.正如我上面提到的,它将因此存储在vec_input
中。Final note: Although unnecessary, you could pass lambda expression per below:最后说明:虽然没有必要,但您可以通过以下 lambda 表达式:
[&scale](double element) -> double { return element *= scale; }
It explicitly states that the output of the lambda expression is a double.它明确指出 lambda 表达式的输出是双精度数。 However, we can omit that, because the compiler, in this case, can deduce the return type by itself.但是,我们可以省略它,因为在这种情况下,编译器可以自己推断返回类型。
I know this not STL as you want, but it is something you can adapt as different needs arise.我知道这不是你想要的 STL,但它是你可以适应不同需求的东西。
Below is a template you can use to calculate;以下是您可以用来计算的模板; 'func' would be the function you want to do: multiply, add, and so on; 'func' 将是您想要执行的函数:乘法、加法等; 'parm' is the second parameter to the 'func'. 'parm' 是 'func' 的第二个参数。 You can easily extend this to take different func's with more parms of varied types.您可以轻松地扩展它以使用更多不同类型的参数来获取不同的函数。
template<typename _ITStart, typename _ITEnd, typename _Func , typename _Value >
_ITStart xform(_ITStart its, _ITEnd ite, _Func func, _Value parm)
{
while (its != ite) { *its = func(*its, parm); its++; }
return its;
}
...
int mul(int a, int b) { return a*b; }
vector< int > v;
xform(v.begin(), v.end(), mul, 3); /* will multiply each element of v by 3 */
Also, this is not a 'safe' function, you must do type/value-checking etc. before you use it.此外,这不是一个“安全”功能,您必须在使用它之前进行类型/值检查等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.