2

I have a functor that creates a linearly spaced set of values . . .

//Linear spaced generator
struct gen_lin {
    float mi, inc;
public:
    gen_lin(float _mi=1.f, float _inc=1.f) : mi(_mi), inc(_inc){};
    float operator()() {
        return  mi+=inc;
    }
};

And I can fill a vector with values like so ...

const size_t elements = 400;
std::vector<float> x(elements);
std::generate_n(x.begin(), elements, gen_lin(10.f,5.f) );

Now, I can easily convert this to a log scale using a lambda like so ...

auto lin = gen_lin(10.f,5.f);
std::generate_n(x.begin(), elements, [&](){return logf(lin());} );

But when I try to squeeze it all on to one line, the vector is entirely filled with the value of logf(10.)

std::generate_n(x.begin(), elements, [](){return logf(  gen_lin(10.f,5.f)() );} );

Why, and is it possible to tweak my last line of code to make it work?

0

3 Answers 3

2

With this, you are creating a single gen_lin object, and using it multiple times:

auto lin = gen_lin(10.f,5.f);
std::generate_n(x.begin(), elements, [&](){return logf(lin());} );

With this, you are creating several gen_lin objects:

std::generate_n(x.begin(), elements, [](){return logf(  gen_lin(10.f,5.f)() );} );

Each time you create a new gen_lin object, the current value gets reset.

2

In the first case:

auto lin = gen_lin(10.f,5.f);
std::generate_n(x.begin(), elements, [&](){return logf(lin());} );

You have a persistent gen_lin object, lin, that gets updated with every call to the lambda. But with your one-liner, you are just creating fresh gen_lin object with every call to the lambda, getting the first value that it returns, and then throwing the object away. Since it's a fresh object, initialized with the same constant values, it's going to give you the same value every time.

1

Each lamdas call creates a new instance of your functor in the second case.

Stuff like bind might fix your problem. Make the lambda take your functor as an argument and use bind to attach a common instance to that argument?

Or use a compose functor of whatever flavour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.