Saving Random Number Generator State in C++11

2019-02-22 11:06发布

问题:

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);

I would like to be able to save the state of myRandomGenerator in the file save.txt. How would I do thi?

回答1:

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);
}