Search code examples
c++stllambdaboost-bind

using std::transform for calling object's function


Suppose I have a vector of shared pointers of objects of class A. I want to collect all the return values of method A::foo for all of the A objects and store them in some container, say another vector. Can this be done with std::transform or std::for_each and std::bind or some boost function ?

class A {

  public:
  string foo(int p);

};

std::vector<shared_ptr<A>> vec;

Solution

  • std::transform is fine for this:

    std::vector<std::string> string_vec;
    const int magic_number = 42;
    std::transform(std::begin(vec),
                  std::end(vec),
                  std::back_inserter(string_vec),
                  [magic_number](std::shared_ptr<A> a){ return a->foo(magic_number); } );
    

    Obviously, you need to figure out which int you want to pass to A::foo(int).

    In C++03, you can replace the lambda by a functor or function:

    struct get_foo
    {
      get_foo(int n) : n_(n) {}
      bool operator() (std::shared_ptr<A> a) const { return a->foo(n); }
    private:
      int n_;
    };
    
    const int magic_number = 42;
    std::vector<std::string> string_vec;
    std::transform(std::begin(vec),
                  std::end(vec),
                  std::back_inserter(string_vec),
                  get_foo(magic_number));