对容器中的每个元素调用成员函数
这个问题是一个风格问题,因为你总是可以编写一个 for 循环或类似的东西; 然而,是否有一个不那么突兀的 STL 或 BOOST 相当于写:
for (container<type>::iterator iter = cointainer.begin();
iter != cointainer.end();
iter++)
iter->func();
?
像(想象的)这样:
call_for_each(container.begin(), container.end(), &Type::func);
我认为如果您决定更改基本类型/容器类型,这将是 1)更少的打字,2)更容易阅读,3)更少的更改。
编辑: 感谢您的帮助,现在,如果我想向成员函数传递一些参数怎么办?
This question is a matter of style, since you can always write a for loop or something similar; however, is there a less obtrusive STL or BOOST equivalent to writing:
for (container<type>::iterator iter = cointainer.begin();
iter != cointainer.end();
iter++)
iter->func();
?
Something like (imagined) this:
call_for_each(container.begin(), container.end(), &Type::func);
I think it would be 1) less typing, 2) easier to read, 3) less changes if you decided to change base type/container type.
EDIT:
Thanks for your help, now, what if I wanted to pass some arguments to the member function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请参阅
std::for_each
和std::bind
文档了解详细信息。错过了您的编辑:无论如何,如果需要的话,这是在不使用 Boost 的情况下实现您想要的效果的另一种方法:
See
std::for_each
andstd::bind
documentation for details.Missed your edit: Anyway here is another way of achieving what you want without using Boost, if ever need be:
您可以使用 std::for_each 或 boost 的 foreach 构造。
当您不想将逻辑移至另一个函数时,请使用 boost 的 BOOST_FOREACH 或 BOOST_REVERSE_FOREACH 。
You can use std::for_each or boost's foreach constructs.
Use boost's BOOST_FOREACH or BOOST_REVERSE_FOREACH when you don't want to move the logic into another function.
我发现 boost bind 似乎非常适合该任务,而且您可以向该方法传递其他参数:
I found out that boost bind seems to be well suited for the task, plus you can pass additional arguments to the method:
自 C++11 标准以来,BOOST 方法使用不同的语法进行标准化,如“基于范围的循环”:
Since C++11 standard the BOOST approach is standardized with different syntax as the "range-based-loop":
如果您确实想提高性能而不仅仅是美化代码,那么您真正需要的是映射函数。 Eric Sink 编写了一个 .net 实现
If you actually want to improve performance rather than just pretty up your code, what you really need is a map function. Eric Sink wrote a .net implementation