c++11 - <random> 获取 rng-engine 的内部状态

标签 c++11

是否可以获得 rng-engine 的内部状态?我考虑实现一个游戏,我想将 rng 引擎的内部状态存储在保存文件中,以便保存和重新加载不会改变游戏。

目前我能想到的唯一可能性是保存种子和从该引擎获取的随机数的数量,但我希望有更优雅的东西。

有什么想法吗? 问候 托比亚斯

最佳答案

来自cppreference :

Engines and distributions are designed to be used together to produce random values. All of the engines may be specifically seeded, serialized, and deserialized for use with repeatable simulators.

您会注意到所有引擎都有 operator<<operator>>定义的。因此,您应该能够使用这些文件保存和加载它们。

概念证明:

#include <fstream>
#include <iostream>
#include <random>

int main(int argc, char* argv[])
{
    std::ofstream ofile("out.dat", std::ios::binary);

    std::random_device randDev;
    std::default_random_engine defEngine(randDev());
    std::uniform_int_distribution<int> dist(0, 9);
    auto printSomeNumbers = [&](std::default_random_engine& engine) { for(int i=0; i < 10; i++) { std::cout << dist(engine) << " "; } std::cout << std::endl; };

    std::cout << "Start sequence: " << std::endl;
    printSomeNumbers(defEngine);

    ofile << defEngine;
    ofile.close();

    std::default_random_engine fileEngine;

    std::ifstream ifile("out.dat", std::ios::binary);
    ifile >> fileEngine;

    std::cout << "Orig engine: "; printSomeNumbers(defEngine);
    std::cout << "File engine: "; printSomeNumbers(fileEngine);

    std::cin.get();
    return 0;
}

可以是seen on Coliru ,输出为:

Start sequence:

6 5 8 2 9 6 5 2 6 3

Orig engine: 0 5 8 5 2 2 0 7 2 0

File engine: 0 5 8 5 2 2 0 7 2 0

关于c++11 - <random> 获取 rng-engine 的内部状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22139647/

相关文章:

c++ - 为 libstdc++ 生成 CTAGS(来自当前的 GCC)

multithreading - C++11 用 clang 替代 OpenMP

c++ - 多态仿函数上的 std::result_of

c++ - 在 C++11 中,如何调用 new 并为对象预留足够的内存?

c++ - '-std=c++11' 对 C++/ObjC++ 有效,但对 C 无效

c++ - 有没有办法为容器类型创建运算符/函数重载

C++11 exit() 和 abs() 不包含 <cstdlib>?

C++11 : Compare lambda expression

c++ - boost::is_nothrow_move_constructible 实现

c++ - 我可以在参数包扩展中调用所有基类的函数吗?