在C ++中保存随机数生成器状态11 [英] Saving Random Number Generator State in C++11
本文介绍了在C ++中保存随机数生成器状态11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想能够在.txt文件中保存随机数生成器的状态并读回。我听说过,使用c ++ 11,这可以使用<<和>>运算符。但是,我不知道我该怎么做。我有一个随机数生成器初始化如下:
I would like to be able to save the state of a random number generator in a .txt file and read it back in. I have heard that with c++11, this can be done using the << and >> operators. However, I'm not sure how exactly I would do this. I have a random number generator initialized as follows:
mt19937 myRandomGenerator(1);
normal_distribution<double> myDistribution(0.0, 1.0);
我想能够在文件save.txt中保存myRandomGenerator的状态。
I would like to be able to save the state of myRandomGenerator in the file save.txt. How would I do thi?
推荐答案
正如所描述的,使用运算符<< / code>并使用
operator>>
读取状态。
It's just as described, write it using operator<<
and read the state back in using operator>>
.
#include <fstream>
#include <random>
#include <cassert>
int main() {
std::mt19937 myRandomGenerator(1);
{
std::ofstream fout("save.txt");
fout << myRandomGenerator;
}
std::ifstream fin("save.txt");
std::mt19937 myRandomGeneratorCopy;
fin >> myRandomGeneratorCopy;
assert(myRandomGenerator == myRandomGeneratorCopy);
}
这篇关于在C ++中保存随机数生成器状态11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文