std::random_shuffle not being seeded

std::random_shuffle not being seeded

本文关键字:being seeded not random std shuffle      更新时间:2023-10-16
#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类)。