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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With