user1096734
user1096734

Reputation:

STL algorithms such as for_each applied to more than one arguments

Is it possible to write something similar to mem_fun and bind1st etc. so that STL algorithms such as for_each can be applied to more than one arguments? Of course, all except one arguments are given, and the one that has not is going to be filled in by the container elements.

Can anyone please give such an example?

Upvotes: 1

Views: 694

Answers (3)

pmr
pmr

Reputation: 59811

What you are looking for is std::bind or its twin boost::bind. They are used like this:

std::vector<int> v = {1,2,3,4};
std::transform(begin(v), end(v), begin(v), std::bind(std::plus<int>(), _1, 23 ));

Also have a look at as many broken ways to iterate as possible https://stackoverflow.com/a/8378613/105672

Upvotes: 5

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

Lambdas, in my opinion, are much clearer. pmr's example with a lambda instead of std::bind:

std::vector<int> v = {1,2,3,4};
std::transform(begin(v), end(v), begin(v), [](int n) { return n + 23 });

Lambdas can also handle with ease situations that are quite a bit more difficult with bind and friends, for example:

std::transform(begin(v), end(v), begin(v), [](int n) { return n * ((double)rand() / RAND_MAX); });

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361322

In C++11, you can do the same which @pmr has posted in this way as well:

std::vector<int> v = {1,2,3,4};
std::transform(begin(v), end(v), begin(v), [](int _1) { return _1 + 23} );

Compare this with @pmr's solution.

Notice that _1 from @pmr solution becomes the parameter of the lambda in my solution. You could (in fact, should) use better name, of course; I used _1 so that you could compare and understand what symbol means what.

Upvotes: 1

Related Questions