使用 for_each 调用容器元素成员的成员函数?
令人困惑的标题,希望一些代码能够澄清:
struct MyNestedType {
void func();
};
struct MyType {
MyNestedType* nested;
}
std::vector<MyType> vec;
// ... populate vec
// I want something approximating this line, but that doesn't use made-up C++!
std::for_each(vec.begin(), vec.end(), std::mem_fun_ref(&MyType::nested->func));
所以基本上我想在容器的每个元素上调用一个方法,但它实际上不是该类型的方法,它是包含类型的一些方法...我知道我可以写一个函数对象来“传递”调用,但是我想调用一些方法,这会变得混乱。
有任何想法吗?
Confusing title, hopefully some code will clarify:
struct MyNestedType {
void func();
};
struct MyType {
MyNestedType* nested;
}
std::vector<MyType> vec;
// ... populate vec
// I want something approximating this line, but that doesn't use made-up C++!
std::for_each(vec.begin(), vec.end(), std::mem_fun_ref(&MyType::nested->func));
So basically I want to call a method on each element of the container, but it's not actually a method of the type, it's some method on a contained type... I know I could write a function object to 'pass on' the call but there are a few methods I'd like to call and that will get messy.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为什么不使用简单的 for 循环呢?
或者,您可以使用 lambda 表达式或 boost::foreach
您可以使用 binder 和 mem_funs 构建 up 表达式,但这会变得非常混乱和混乱! 将所有内容都放在一行 std::foreach 中没有任何优势。
Why don't you just use a simple for-loop?
Alternatively, you could use lambda expressions or boost::foreach
You can build your up expression with binders and mem_funs, but this will get very messy and confusing! There is no advantage in putting everything in one std::foreach line.
您可以使用这样的函子
来解决您的问题
You can use such functor
To solve your problem
也许你可以将 func() 添加到 struct MyType() 中:
这样你就不会拥有单独的适配器函子,而是包装类型内的聚合,即相当常规的 OOP 技术。
Maybe you could add func() into struct MyType():
This way you will not have separate adapter functor, but instead an aggregation inside wrapper type, i.e. quite regular OOP technique.
如果你想使用 for_each 你需要一个函子。
描述的 boost::FOREACH 语法
或者,我会使用Dario: 使用 for_each 调用容器元素成员的成员函数?
If you want to use for_each you need a functor.
Alternatively I would use the boost::FOREACH syntax described by:
Dario: Call member functions of members of elements of a container with for_each?
是的,可以使用
boost::bind
来实现此目的,但它会变得混乱。 请使用 @Dario 的 boost for-each 方式,但为了完整起见,这里是boost::bind
无论如何,碰巧的是,我们甚至没有得到一个很好的单行文字:)
Yes it is possible to use
boost::bind
for this, but it gets messy. Please use @Dario's boost for-each way, but here is theboost::bind
one for the sake of completenessAnyway, as it happens, we don't even get a nice one-liner with this :)
使用 Boost 的
transform_iterator
怎么样? ?How about using Boost's
transform_iterator
?