gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:06:50 26 4
gpt4 key购买 nike

是否可以获得 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/

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