代码之家  ›  专栏  ›  技术社区  ›  bradtgmurray

如何将对象的成员函数调用为std算法的unary_function?

  •  4
  • bradtgmurray  · 技术社区  · 17 年前

    我有一个类,看起来像这样。

    class A 
    {
    public:
        void doSomething();
    }
    

    我有一系列这样的课程。我想对数组中的每个项目调用doSomething()。使用algorithms标头最简单的方法是什么?

    1 回复  |  直到 17 年前
        1
  •  8
  •   bradtgmurray    17 年前

    使用std::mem_fun_ref将成员函数包装为一元函数。

    #include <algoritm>
    #include <functional>
    
    std::vector<A> the_vector;
    
    ...
    
    std::for_each(the_vector.begin(), the_vector.end(),
                  std::mem_fun_ref(&A::doSomething));
    

    std::vector<A*> the_vector;
    
    ...
    
    std::for_each(the_vector.begin(), the_vector.end(),
                  std::mem_fun(&A::doSomething));