Vorac
Vorac

Reputation: 9114

How to use for_each with additional parameters?

I am trying to figure out how is for_each() used. First, I transformed this loop

for(int i = 0; i < myvector.size(); ++i){
    myvector[i].a.b. = true;
}

into

auto enable [](Myvect &mv) {mv.a.b = true;};
for_each(myvector.begin(), myvector.end(), enable);

This worked fine.


Now I would like to use the for_each construct for the following loop:

for(int i = 0; i < myvector.size(); ++i){
    foo(local_var, myvector[i]);
}

Is this possible?

Upvotes: 0

Views: 78

Answers (1)

P0W
P0W

Reputation: 47784

You can simply put foo inside lambda function :

for_each( myvector.begin(), myvector.end(), 
                           [local_var](Myvect& mv) // notice reference
                           { 
                           // Assuming you want to modify mv
                              foo(local_var, mv ); 
                           }
        );

Upvotes: 1

Related Questions