在一个容器中的每个元素调用成员函数 [英] Call member function on each element in a container

查看:160
本文介绍了在一个容器中的每个元素调用成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这问题是风格问题,因为你总是可以写一个for循环或类似的东西;但是,有没有那么突兀STL或升压相当于写:

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);

我认为这将是1)少打字,2)更容易阅读,3)少变化,如果你决定改变基本类型/容器类型。

I think it would be 1) less typing, 2) easier to read, 3) less changes if you decided to change base type/container type.

编辑:
感谢您的帮助,现在,如果我想一些参数传递给成员函数是什么?

Thanks for your help, now, what if I wanted to pass some arguments to the member function?

推荐答案

我发现升压结合似乎是非常适合的任务,再加上你可以通过其他参数的方法:

I found out that boost bind seems to be well suited for the task, plus you can pass additional arguments to the method:

#include <iostream>
#include <functional>
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>

struct Foo {
    Foo(int value) : value_(value) {
    }

    void func(int value) {
        std::cout << "member = " << value_ << " argument = " << value << std::endl;
    }

private:
    int value_;
};

int main() {
    std::vector<Foo> foo_vector;

    for (int i = 0; i < 5; i++)
        foo_vector.push_back(Foo(i));

    std::for_each(foo_vector.begin(), foo_vector.end(),
        boost::bind(&Foo::func, _1, 1));
}

这篇关于在一个容器中的每个元素调用成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆