[英]Vector manipulation using STL algorithms
I have a vector and I would like to multiply each of its elements with a scalar value. 我有一个向量,我想将其每个元素与标量值相乘。 I wrote the following code for this 我为此编写了以下代码
int func(const int x)
{
return 10 * x; // say the scalar value is 10
}
void foo()
{
// .. compute vector vert
std::transform(vert.begin(), vert.end(), vert.begin(), ::func);
}
The code does the job, but I was wondering if there is a more concise implementation possible for this, one that does not require me to define the func function seperately 代码可以完成这项工作,但是我想知道是否有一种更简洁的实现可能,不需要我单独定义func函数。
I still have yet to see a case where transform()
actually looks like a good answer... I would strongly suggest: 我仍然没有看到一个情况,其中transform()
实际上看起来像是一个很好的答案...我强烈建议:
for (int& x : vert) {
x *= 10; // or x = func(x)
}
It's clearer and more concise. 更清晰,更简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.