std::random_shuffle not being seeded
std::random_shuffle not being seeded
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
int main() {
std::vector<short> a(256);
for (short x = 0; x != 256; ++x) {
a[x] = x;
}
for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
std::cout << std::endl;
std::srand(11);
std::random_shuffle(a.begin(), a.end());
for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
std::cout << std::endl;
for (short x = 0; x != 256; ++x) {
a[x] = x;
}
for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
std::cout << std::endl;
std::srand(11);
std::random_shuffle(a.begin(), a.end());
for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
}
所以,这是我的代码。显然,我所期望的是两次相同的洗牌。我得到的是,虽然两次发射之间的洗牌是一致的,但它们是不同的,似乎忽略了srand!我在这里做错了什么?
请注意,对于std::random_shuffle
使用的随机数生成器是实现定义的,则不能保证使用std::rand
。
你可以改用std::shuffle
,并给它传递一个随机数生成器:
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(a.begin(), a.end(), g);
住
首先请注意,您使用的std::random_shuffle
版本已被弃用。
另请注意(来自上一个参考链接)
。经常使用
std::rand
函数。
这里的关键词是经常而不是总是。
如果要确保始终创建相同的序列,则应使用替代方法之一,传递特定的随机数函数,或使用传递生成器的std::shuffle
函数(来自C++11"新"PRNG类)。
相关文章:
- 删除分配的 (?) 指针时"Pointer being freed was not allocated"
- D-lang being faster than C++?
- C++编译错误,"malloc: *** error for object: pointer being freed was not allocated"
- 创建一个移动分配函数,不断得到"pointer being freed was not allocated"
- C++ "Pure Virtual Function Being Called"失败
- qt resources qrc not being found
- 解析 csv 文件,"malloc: *** error for object 0x7ffeeb4f4b80: pointer being freed was not allocated"出现此错误
- C++ "pointer being freed was not allocated"
- 构造函数未被调用并"pointer being freed was not allocated"错误
- std::random_shuffle not being seeded
- "A uses B, which is being defined"是什么意思?
- C++: strcmp being ignored
- 结构"pointer being freed was not allocated"
- OnKillFocus not being called
- 当我弹出时,我收到"pointer being freed was not allocated"错误
- 调试"malloc error: pointer being freed was not allocated" ,使用 gdb
- 在堆上创建的对象是否可以被视为C++中的'being on stack'?
- 未命名的命名空间和 iostream 会导致"!= being illegal operation"
- 又是"pointer being freed was not allocated"
- cin / cout being skipped