A Random can be copied, saved, and restored in a variety of ways as illustrated here by RandomSave.cpp
#include <iostream>
#include <fstream>
#include <string>
#if HAVE_BOOST_SERIALIZATION
#if defined(_MSC_VER)
#pragma warning (disable: 4244 4996)
#endif
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#endif
int retval = 0;
long step = 1000000;
std::cout << "Using " << r.Name() << "\n"
<< "with seed " << r.SeedString() << "\n";
r.StepCount(step);
{
std::cout << "Test save and restore with copy constructor... ";
r.StepCount(step); s.StepCount(step);
std::cout << (r == s && r() == s()
? "succeeded\n" : (retval = 1, "failed\n"));
}
{
std::cout << "Test save state via count... ";
long long savecount = r.Count();
r.StepCount(step);
r.SetCount(savecount);
std::cout << (d == r.
Fixed()
? "succeeded\n" : (retval = 1, "failed\n"));
}
{
std::cout << "Test save state via seed and count... ";
s.SetCount(r.Count());
r.StepCount(step); s.StepCount(step);
std::cout << (r == s && r() == s()
? "succeeded\n" : (retval = 1, "failed\n"));
}
{
std::cout << "Test save state to file in portable binary format... ";
{
std::ofstream f("rand.bin", std::ios::binary);
r.Save(f);
}
{
std::ifstream f("rand.bin", std::ios::binary);
s.Load(f);
}
r.StepCount(step); s.StepCount(step);
std::cout << (r == s && r() == s()
? "succeeded\n" : (retval = 1, "failed\n"));
}
{
std::cout << "Test save state to file in text format... ";
{
std::ofstream f("rand.txt");
f << "Random number state:\n" << r << "\n";
}
{
std::ifstream f("rand.txt");
std::string str;
std::getline(f, str);
f >> s;
}
r.StepCount(step); s.StepCount(step);
std::cout << (r == s && r() == s()
? "succeeded\n" : (retval = 1, "failed\n"));
}
{
#if HAVE_BOOST_SERIALIZATION
std::cout << "Test save state to file in boost xml format... ";
{
std::ofstream f("rand.xml");
boost::archive::xml_oarchive oa(f);
oa << BOOST_SERIALIZATION_NVP(r);
}
{
std::ifstream f("rand.xml");
boost::archive::xml_iarchive ia(f);
ia >> BOOST_SERIALIZATION_NVP(s);
}
r.StepCount(step); s.StepCount(step);
std::cout << (r == s && r() == s()
? "succeeded\n" : (retval = 1, "failed\n"));
#else
std::cout << "Skipping boost tests\n";
#endif
}
return retval;
}
As you can see in this example, you can use Boost serialization to save and restore the state of a Random object to various types of archives provided you have the Boost serialization library installed (see http://www.boost.org). To turn this feature on, compile any code which includes RandomLib/Random.hpp with HAVE_BOOST_SERIALIZATION defined to be 1, and link the resulting code with libboost_serialization. In order to declare the boost archives, you will need to include the appropriate header file, e.g.,