c++的random_shuffle总是给出相同的结果
C++ random_shuffle is always giving the same results
下面对随机洗牌的调用总是对向量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("%dn", 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
OP的评论清楚地表明他们使用的是Clang和libc++,而不是GCC/libstdc++。
快速查看libc++的random_shuffle
实现,可以看出它使用__rs_default
类型的对象作为其随机性的来源,检查__rs_default
的实现可以看出它只是使用默认构造的std::mt19937
对象:
__rs_default::result_type
__rs_default::operator()()
{
static mt19937 __rs_g;
return __rs_g();
}
换句话说,在这个实现中,srand
对random_shuffle
的双参数版本所使用的"随机性"来源没有任何影响。(吓人的引号是因为它总是使用一个固定的种子。)注意,random_shuffle
根本不需要使用rand
,所以你不能指望srand
在可移植代码中"工作"。
使用std::shuffle
和<random>
设施。
首先,-std=c++0x
和-std=c++11
表示完全相同,所以测试它们是没有意义的。
你没有提供一个完整的程序(请阅读https://stackoverflow.com/help/mcve下次),所以我猜剩下的代码,我试着这样做:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
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 : v)
std::cout << i << ' ';
std::cout << std::endl;
}
我每秒钟得到不同的结果:
tmp$ ./a.out
2 1 8 5 9 7 6 3 10 4
tmp$ ./a.out
10 7 6 3 1 8 9 4 5 2
tmp$ ./a.out
4 7 3 6 5 8 1 9 10 2
tmp$ ./a.out
4 7 3 6 5 8 1 9 10 2
tmp$ ./a.out
4 7 3 6 5 8 1 9 10 2
tmp$ ./a.out
10 2 6 3 9 4 5 7 8 1
tmp$ ./a.out
10 2 6 3 9 4 5 7 8 1
tmp$ ./a.out
10 2 6 3 9 4 5 7 8 1
tmp$ ./a.out
2 1 3 7 5 8 9 6 4 10
产生相同结果的次数是因为time(0)
返回的秒数是相同的,因此rand()
函数的种子是相同的,因此结果是相同的。如果您等待一秒钟,以便time(0)
返回不同的值,您应该得到元素的不同随机洗牌。
如果你运行的代码和我的不一样,你可能会得到不同的结果,但我们无法解释结果,因为你没有给我们看你的代码。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- 如何让C++'tally up'结果并制定计划?
- 为什么这个程序的结果是3 "born"?和 4 死
- 为什么<random>库在使用 std::uniform_int_distribution 时每次都产生相同的结果