简体   繁体   中英

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.

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?

You can use std::for_each for this:

#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; });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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