Just another site

Archive for the month “May, 2012”

Vectors and constructors with rand()

So here is a silly mistake I just made; say Foo is a class whose constructor includes setting a variable randomly and you want a population of Foos, then

vector foos(n,foo);

isn’t what you want, this only calls the Foo constructor once and then makes n copies of the result, so the random value is the same for each instance! You need

vector foos;
for(int i=0;i<n;++)
Foo foo;


Post Navigation