而不是手动输入数组中的数字,我该如何在数组中随机生成这10个数字?他们可以在任何位置,只是需要这10个号码如何使用rand()生成数组中的数字
int array[length] = { 1000, 2000,3000,4000,5000,6000,7000, 8000, 9000, 10000};
而不是手动输入数组中的数字,我该如何在数组中随机生成这10个数字?他们可以在任何位置,只是需要这10个号码如何使用rand()生成数组中的数字
int array[length] = { 1000, 2000,3000,4000,5000,6000,7000, 8000, 9000, 10000};
您可以使用std::shuffle
到重排列您的阵列随机(改编自reference documentation sample)中的数字的位置:
const size_t length = 10;
int array[length] = { 1000, 2000,3000,4000,5000,6000,7000, 8000, 9000, 10000};
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(std::begin(array), std::end(array), g);
在shuffle()
调用后,值出现在array
的随机位置。
@ user4581301肯定是_petit mal absence_(可能咖啡不够),我最后完成了(1小时laterz ;-P) –
什么是mt19937 g(rd()); – TheOptimist
A [标准随机生成器引擎](http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine)。 –
如果您想使用非库算法,您可以将数组中的每个元素与位于随机确定位置的另一个元素进行切换。在代码中,它看起来像这样:
int array[length] = {1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
srand(time(NULL));
int randompos, temp;
for (int i = 0; i < length; i++) {
randompos = rand % 10;
temp = array[i];
array[i] = array[randompos];
array[randompos] = temp;
//here, you could have a cout << array[randompos] << " "; to test
}
使用['的std :: random_shuffle()'](http://en.cppreference.com/w/cpp/algorithm/random_shuffle) –
怎么办我正好用那个? – TheOptimist
请看我的答案。 –