gpt4 book ai didi

c++ - std::random_shuffle 未播种

转载 作者:搜寻专家 更新时间:2023-10-31 00:57:46 47 4
gpt4 key购买 nike

#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);

LIVE

关于c++ - std::random_shuffle 未播种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786007/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com