Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save the state of std::mersenne_twister_engine to restore it later?

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?

like image 849
fbrereto Avatar asked Sep 06 '25 03:09

fbrereto


2 Answers

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

like image 75
zahir Avatar answered Sep 07 '25 22:09

zahir


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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!