Nov 16, 2010 at 12:32am UTC
how would I go about randomizing both objects and integers in an array of any size?
Nov 16, 2010 at 4:30am UTC
Well, what I would do is cast the array you want to randomize as a char array, and loop through it setting each index as rand()%256. Something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void * randomize_array(void * array,int numobj,int objsize){
char * chr_array=(char *)array;
int size=numobj*objsize;
for (int x=0;x<size;++x){
chr_array[x]=rand()%256;}
return array;}
//or with templates
template <typename T>
T* randomize_array(T* array,int size){
char * chr_array=(char *)array;
size*=sizeof (T);
for (int x=0;x<size;++x){
chr_array[x]=rand()%256;}
return array;}
With both cases, make sure to call srand(time(0)) before using them, to seed the random function.
Last edited on Nov 16, 2010 at 4:32am UTC
Nov 16, 2010 at 4:32am UTC
For non-trivial classes, won't that possibly mess up the vtables?
Nov 16, 2010 at 2:30pm UTC
+1 sohguanh
Yes, above randomize_array functions are very easy to misuse.