使用STL算法的经典示例:
void foo(int){};
vector<int> collection;
collection.push_back(3);
collection.push_back(4);
... etc.
std::for_each(collection.begin(), collection.end(), bind(foo, _1));
Run Code Online (Sandbox Code Playgroud)
但是,如果我们有多个函数,需要使用相同的参数值调用,该怎么办:
void bar(int){};
void beer(int){};
... etc.
Run Code Online (Sandbox Code Playgroud)
每次使用不同的函数重复for_each算法都不是选项.我需要更优雅的解决方案.
由于您使用了标记问题C++11,因此您可以将lambda用作:
std::for_each(collection.begin(), collection.end(), [](int a)
{
bar(a);
beer(a);
});
Run Code Online (Sandbox Code Playgroud)
我记得C++ 11具有std::begin和std::end作为自由函数,它应该比成员函数更受欢迎:
std::for_each(std::begin(collection), std::end(collection), [](int a)
{
bar(a);
beer(a);
});
Run Code Online (Sandbox Code Playgroud)
自由函数应该首选的基本原理是因为现在,例如,如果您将集合的类型更改为简单数组(例如int collection[100]),那么上面的代码可以正常工作而无需更改单个字符.使用新的标准C++,自由函数将比成员函数更加统一使用.
或者,您可以使用基于范围的 for循环:
for(int a : collection)
{
bar(a);
beer(a);
}
Run Code Online (Sandbox Code Playgroud)
啊! 它看起来更好.整洁干净,没有begin和end在所有.
这将是一个使用lambdas的好地方:
#include <vector>
#include <algorithm>
void bar(int){};
void beer(int){};
int main()
{
std::vector<int> collection;
collection.push_back(3);
collection.push_back(4);
std::for_each(collection.begin(), collection.end(),
[](int i) {bar(i); beer(i);});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |