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?

2
  • 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);. Commented Nov 30, 2009 at 13:05
  • may be I can do that, but still I would like to know why this approach won't work. Commented Nov 30, 2009 at 13:06

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks..that worked perfectly, I'll check on how delayed function calls work.
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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.