简体   繁体   English

STL算法(例如for_each)应用于多个参数

[英]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? 是否可以编写类似于mem_funbind1st等的东西,以便可以将for_each STL算法应用于多个参数? 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? 有人可以举这样的例子吗?

What you are looking for is std::bind or its twin boost::bind . 您正在寻找的是std :: bind或其双胞胎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 还请看一下尽可能多的迭代迭代方法https://stackoverflow.com/a/8378613/105672

Lambdas, in my opinion, are much clearer. 我认为Lambda更清晰。 pmr's example with a lambda instead of std::bind : 带有lambda而不是std::bind pmr示例:

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: Lambda还可轻松处理绑定和好友遇到的困难情况,例如:

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

In C++11, you can do the same which @pmr has posted in this way as well: 在C ++ 11中,您也可以执行@pmr通过这种方式发布的操作:

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. 将此与@pmr的解决方案进行比较。

Notice that _1 from @pmr solution becomes the parameter of the lambda in my solution. 请注意,来自@pmr解决方案的_1成为我的解决方案中lambda的参数。 You could (in fact, should ) use better name, of course; 当然,您可以(实际上应该 )使用更好的名称; I used _1 so that you could compare and understand what symbol means what. 我使用了_1以便您可以比较并理解什么符号表示什么。

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

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