2

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?

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • You don't need to use boost::lambda to fill the array with random numbers, by the way. You could e.g. use `std::generate(a.begin(), a.end(), &rand);`. – MP24 Nov 30 '09 at 13:05
  • may be I can do that, but still I would like to know why this approach won't work. – Naveen Nov 30 '09 at 13:06

2 Answers2

10

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

4

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);
Luc Touraille
  • 79,925
  • 15
  • 92
  • 137