deko
deko

Reputation: 2636

Calling a function with several arguments for every element in a collection

I've got a collection, for example, std::vector<MyClass> elements; and want to run a function for every element.

It's simple and transparent when the function has no arguments: std::for_each(elements.begin(), elements.end(), std::mem_fun(&MyClass::MyFunction));

The code starts looking ugly when the function has 1 argument and I need to use std::bind_2nd.

Is there a way (perhaps, using lambdas) to write a function call with several arguments?

Upvotes: 1

Views: 79

Answers (2)

IceFire
IceFire

Reputation: 4147

for_each works but as you said it might look less readable. I prefer the range-based for syntax a lot:

for(auto& element : elements)
    element.foo( … );

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

Your code

std::for_each(v.begin(), v.end(), std::mem_fun(&MyClass::MyFunction));

is equivalent to

std::for_each(v.begin(), v.end(), [](auto& obj) { obj.MyFunction(); });

Now that the invocation of MyFunction is done in your code, you can pass other parameters to it as needed:

std::string arg1 = "hello";
int arg2 = 123;
std::for_each(v.begin(), v.end(), [&](auto& obj) { obj.MyFunction(arg1, arg2); });

Demo.

Upvotes: 5

Related Questions