【发布时间】:2016-10-04 21:03:11
【问题描述】:
以下对随机洗牌的调用总是为向量 v 提供相同的结果
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main(){
vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
srand(time(0));
random_shuffle(v.begin(), v.end());
for (int i = 0; i < v.size(); ++i) printf("%d ", v[i]); printf("\n");
printf("%d\n", rand() % 100);
return 0;
}
我试过用
编译g++ -std=c++0x
g++ -std=c++11
但是每次都给出相同的结果,所以我不太明白发生了什么。
$./a.out
7 1 4 6 8 9 5 2 3 10
26
$ ./a.out
7 1 4 6 8 9 5 2 3 10
41
$ ./a.out
7 1 4 6 8 9 5 2 3 10
39
【问题讨论】:
-
您在哪里/何时致电
srand(time(0));?你是如何测试的? -
欢迎使用stackoverflow,请在询问“为什么这段代码不起作用?”时提供一个完整程序所以我们不必浪费时间添加您面前已经存在的缺失代码。
-
@AnaEchavarria 它总是为我生成不同的结果。但是,如果在同一秒内启动,它必须始终生成相同的结果。
-
这是clang/libc++。他们的
random_shuffle不使用rand作为随机源。