Search code examples
c++vectormapreducestdvector

Issue by implementing a python like "map" function in C++ : call a class member function


I have a function member :

double XC::nz(double z){
    return pow(z/zrange_0,2)*exp(-pow(z/zrange_0,1.5));
}

I would like to get the equivalent but with vector form, so I did :

vector<double> XC::nz_vec(vector<double> input){

    vector<double> output;
    output.resize(input.size());
    transform(input.begin(), input.end(), output.begin(), nz);
    return output;
}

But compilation is not passed since the call to nz function, especially into transform(input.begin(), input.end(), output.begin(), nz).

So, I saw an alternative that could be :

    transform(input.begin(), input.end(), output.begin(), this->*nz);

but compiler still complains.

In my header, I have put :

class XC{

...

public:    
       double nz(double);
       vector<double> nz_vec(vector<double>);

}

How to circumvent this issue since I want to do in another method of the same class :

int numPoints = 100000;
vector<double> nz_vec_min = nz_vec(linspace(zmin[0], zmin[1], numPoints));
vector<double> nz_vec_max = nz_vec(linspace(zmax[0], zmax[1], numPoints));

with linspace that returns a vector (like in Python)?

I can set the compiler flag -std=c++11 or earlier.


Solution

  • The problem is that nz is a member function and therefore needs to be called on its associated object. The easiest way to do this is with a capturing lambda:

    std::transform(input.begin(), input.end(), output.begin(), [this] (double d) { return nz (d); });
    

    Also, I suggest you pass input by const reference, rather than by value, since the latter makes a copy.

    Live demo