vendredi 22 novembre 2019

why and how to use bind() as predicate in c++?

I'm given this strange-looking std::generate() function which create a std::vector of random number between a and b.

int myrand(int a, int b)
{
    int div = b-a;
    return a + (rand() % (b-a));
}

int main()
{
    vector<int> v(20);
    generate( v.begin(), v.end(), bind(myrand,1, 11) );  //fill with random no. bwt 1 and 10 
    return 0;
}

I know how std::generate() function works, one has to pass a predicate into the third argument. Predicate can be in the form of a function, function object, or function pointer.

But i'm quite confused by the expression bind(myrand,1, 11), why we have to write it this way?

I know that bind returns a function which can be placed as the third argument here.

But, isn't myrand a function as well? I've tried to replace the third argument with myrand(1,11) and it won't work, why is it so?

Aucun commentaire:

Enregistrer un commentaire