Question

Hey i am trying to transform a vectors of pointers to an object into another vector of pointers to a different object.

I have been given the following classes:

class Test;
class Test2 {
    public:
        Test2(Test*);
}

I am unfamiliar on how to create a functor. this is part of a sample exam for exams later this week i am confused on this question though. The following link explains the use of transform quite well but my problem is a little different. Any help would be great!

Reference: http://www.cplusplus.com/reference/algorithm/transform/

Was it helpful?

Solution

A functor is one which overloads operator(). So you can define a functor as:

struct Test2Generator
{
     //this will be called from std::transform
     Test2* operator()(Test1 *param) const
     {
          return new Test2(param);
     }
};

Then use it as:

std::vector<Test1*> v1;
//fill v1

std::vector<Test2*> v2(v1.size());

std::transform(v1.begin(), v1.end(), v2.begin(), Test2Generator());

In C++11, you don't need to define functor, instead you can use lambda as:

std::transform(v1.begin(), 
               v1.end(), 
               v2.begin(), 
               [](Test1 *param) { return new Test2(param); });

OTHER TIPS

The call to transform will be something similar to:

std::vector<Test*> src = ...
std::vector<Test2*> dst;
dst.reserve( src.size() );
std::transform( src.begin(), src.end(), std::back_inserter(dst), MyFunctor() );

Where MyFunctor() is a function object that implements Test2* operator()( Test* ):

struct MyFunctor {
   Test2* operator()( Test* ) const {
      // implementation goes here
   }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top