繁体   English   中英

在容器中的每个元素上调用成员函数

[英]Call member function on each element in a container

这个问题是一个风格问题,因为你总是可以写一个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)如果您决定更改基本类型/容器类型,更少的更改。

编辑:谢谢你的帮助,现在,如果我想将一些参数传递给成员函数怎么办?

 #include <algorithm>  // for_each
 #include <functional> // bind

 // ...

 std::for_each(container.begin(), container.end(), 
                   std::bind(&Type::func));

有关详细信息,请参阅std::for_eachstd::bind文档。

错过了您的编辑:无论如何,这里是另一种实现您想要的方式而不使用Boost,如果需要的话:

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

你可以使用std :: for_eachboost的foreach结构

当您不想将逻辑移动到另一个函数时,请使用boost的BOOST_FOREACH或BOOST_REVERSE_FOREACH。

我发现boost绑定似乎非常适合该任务,另外你可以向该方法传递额外的参数:

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

如果您真的想要提高性能而不仅仅是提高代码,那么您真正需要的是地图功能。 Eric Sink写了一个.net实现

暂无
暂无

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

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