Passing a C ++ member function Pointer to an STL algorithm

I have a member function as follows:

class XYZ{
public:
    float function(float x);
private:
    float m_DensityMin;
    float m_DensityMax;
};

Now I am trying to convert std::vector<float> foousing the std::transformSTL algorithm by passing a member function functionand storing the resulting values ​​in a vector bar.

If I use this function as a global function, with random data that class member variables should indicate, it works fine.

However, since a function requires the use of member variables m_DensityMinand a m_DensityMaxclass, I need to use it as a member function. This is what I tried:

std::transform(foo.begin(), foo.end(), bar.begin(), &XYZ::function);

but in the end I get an error in VS2010:

error C2065: term does not evaluate to a function taking 1 arguments

, . ? question, std:: mem_fun, std:: mem_fn , .

+4
3

std::mem_fun -, , operator(). , bind XYZ , std::transform:

XYZ xyz;

std::transform(foo.begin(), foo.end(),
               std::back_inserter(bar),
               std::bind1st(std::mem_fun(&XYZ::function), &xyz));
//                  ~~~~~~^      ~~~~~~^                  ~~~^

DEMO

+6

static, . . , , , .

, , XYZ , .

std::transform(foo.begin(),
               foo.end(),
               std::back_inserter(bar),
               [](float a){ return XYZ{}.function(a); });

, , static, XYZ float.

+2

lambda version

std::vector<float> foo;
std::vector<float> bar;
foo.push_back(1.0f);
foo.push_back(2.0f);
XYZ xyz;
std::transform(foo.begin(), foo.end(), std::back_inserter(bar), 
        [&xyz](float& a){ return xyz.function(a); });
 for ( auto & x : bar)
   std::cout<<x<<"\n";
0

Source: https://habr.com/ru/post/1589047/


All Articles