template <typename T>
void shuffle (T* a, int n)
{
//暫時變數放內圈, 使得『多數舊式』編譯器可以最佳化
while (n > 1)
{
int j = rand() % n;
n--;
T t (a[j]); a[j] = a[n]; a[n] = t;
}
}
測試:
#include <time.h>
#include <conio.h>
#include <iostream>
using namespace std;
struct Num {int i;};
int main ()
{
srand(time(0));
int a[10] = {0,1,2,3,4,5,6,7,8,9};
char b[ ] = "abcdefghij";
Num c[10] = {0,1,2,3,4,5,6,7,8,9};
shuffle (a, 10);
shuffle (b, 10);
shuffle (c, 10);
int i;
puts(""); for (i=0;i<10;++i) cout <<' '<<a[i];
puts(""); for (i=0;i<10;++i) cout <<' '<<b[i];
puts(""); for (i=0;i<10;++i) cout <<' '<<c[i].i;
return getch();
}
沒有留言:
張貼留言