Question

I would like to save the state of a std::mersenne_twister_engine so that I can restore it back exactly at a later time. I know I can save the original seed and call discard to roll the engine forward some number of steps, but that requires knowledge of the number of times the engine was advanced, not to mention discard seems like an inefficient (O(N)) way to roll the engine forward.

How do I go about saving off the exact state of the engine?

Was it helpful?

Solution

According to this, engine should support serialization into and from a standard stream.

OTHER TIPS

Just make a copy of it using the copy constructor, and then make an assignment when you want to restore the saved state (or use the copy, or however you want to structure your code).

int main()
{
  mtt19937 engine(10);

  std::cout 
    << engine() << "\n"
    << engine() << "\n"
    << engine() << "\n"
    << engine() << "\n"
    << engine() << "\n\n";

  std::cout << "Making Copy\n\n";

  mtt19937 copy(engine);

  std::cout 
    << engine() << "\n" 
    << engine() << "\n" 
    << engine() << "\n" 
    << engine() << "\n"
    << engine() << "\n";

  std::cout << "----\n";
  engine = copy;

  std::cout 
    << engine() << "\n" 
    << engine() << "\n" 
    << engine() << "\n" 
    << engine() << "\n"
    << engine() << "\n";
}

Output:

266666648
1113235983
1006007037
1572197236
322379391

Making Copy

1241299006
1359151196
1840219852
755708724
110209057
----
1241299006
1359151196
1840219852
755708724
110209057
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top