【问题标题】:std::random_shuffle not being seededstd::random_shuffle 未播种
【发布时间】:2016-08-15 14:57:24
【问题描述】:
#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!我在这里做错了什么?

【问题讨论】:

    标签: c++ random random-seed


    【解决方案1】:

    首先请注意,您使用的std::random_shuffle 版本已被弃用。

    另请注意(来自上一个参考链接)

    ...经常使用std::rand这个函数。

    这里的关键字是经常而不是总是

    如果您想确保始终创建相同的序列,那么您应该使用其中一种替代方法,传递特定的随机数函数,或者使用传递生成器的 std::shuffle 函数(来自 C++ 11 个“新”PRNG classes)。

    【讨论】:

      【解决方案2】:

      请注意,std::random_shuffle 使用的随机数生成器是实现定义的,不保证使用std::rand

      您可以改用std::shuffle 并将其传递给随机数生成器:

      std::random_device rd;
      std::mt19937 g(rd());
      std::shuffle(a.begin(), a.end(), g);
      

      LIVE

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-08
        • 1970-01-01
        • 2020-07-23
        • 2021-08-14
        • 1970-01-01
        相关资源
        最近更新 更多