Question

I am new to boost and trying to write some simple programs to understand it. Here in the following piece of code I am trying to fill an array with random numbers. Here is my code:

    using namespace boost::lambda;
    srand(time(NULL));
    boost::array<int,100> a;
    std::for_each(a.begin(), a.end(), _1=rand());

But it looks like rand() is getting evaluated only once and my array is containing the same values for every element. Can anybody point what is wrong with this code?

Was it helpful?

Solution

Seems like you need to use delayed function call

std::for_each(a.begin(), a.end(), boost::lambda::_1= boost::lambda::bind(rand) );

Here is another interesting situation: Delaying constants and variables

OTHER TIPS

Your code is equivalent to the following one:

using namespace boost::lambda;

srand(time(NULL));

boost::array<int, 100> a;
int i = rand();

std::for_each(a.begin(), a.end(), _1=i);

What you want is rand to be invoked for each element; this is usually done using std::generate, as @MP24 noted in a comment:

std::generate(a.begin(), a.end(), rand);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top