randomizing elements in an array

how would I go about randomizing both objects and integers in an array of any size?
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
For non-trivial classes, won't that possibly mess up the vtables?
If you are allowed to use standard C++ algorithm classes

http://www.cplusplus.com/reference/algorithm/random_shuffle/
+1 sohguanh

Yes, above randomize_array functions are very easy to misuse.
Topic archived. No new replies allowed.