c++ - using std::transform for calling object's function -
suppose have vector of shared pointers of objects of class a. want collect return values of method a::foo of objects , store them in container, vector. can done std::transform
or std::for_each
, std::bind
or boost
function ?
class { public: string foo(int p); }; std::vector<shared_ptr<a>> vec;
std::transform
fine 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, need figure out int
want pass a::foo(int)
.
in c++03, can replace lambda 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));
Comments
Post a Comment