简体   繁体   English

更新C ++向量中的所有元素

[英]Updating all elements in a C++ vector

I have a vector of structs - say the struct is something like: 我有一个结构的向量 - 说结构是这样的:

struct foo {
  int bar1;
  int bar2;
}

Now I want to update each element of my vector and the update is multiplying bar1 by 2. 现在我想更新向量的每个元素,更新将bar1乘以2。

The naive way to do this would be to iterate over each element of the vector, but is there a better way of doing this, maybe by using a library function with a c++11 lambda function? 这样做的天真方法是迭代向量的每个元素,但有没有更好的方法来实现这一点,可能是通过使用带有c ++ 11 lambda函数的库函数?

You can use std::for_each for this: 您可以使用std::for_each

#include <algorithm>
#include <vector>
...
std::vector<foo> v;
....
std::for_each(v.begin(), v.end(), [](foo& f) { f.bar1 *=2; });

Whether it is clearer/simpler than a plain loop is another matter. 它是否比普通循环更清晰/更简单是另一回事。 In this simple case, a plain range based loop might be a better option: 在这个简单的例子中,基于普通范围的循环可能是更好的选择:

for (auto& f : v) f.bar1 *= 2;
#include <algorithm> // for std::for_each
#include <vector>

void update_foos(std::vector<foo>& foos)
{
   // Range-based for
   for(auto& foo : foos)
   {
     foo.bar1 *= 2;
   }
   // std::for_each+lambda
   std::for_each(std::begin(foos), std::end(foos), [](foo& f) { f.bar1 *=2; });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM