我想保存std::mersenne_twister_engine
的状态,以便我可以在以后确切地恢复它。我知道我可以保存原始种子并致电discard
向前推进引擎一些步骤,但这需要了解引擎推进的次数,更不用说discard
似乎是低效(O(N)
)方式推动引擎前进。
如何保存发动机的准确状态?
答案 0 :(得分:6)
根据this,引擎应该支持在标准流中进行序列化。
答案 1 :(得分:2)
只需使用复制构造函数复制它,然后在想要恢复已保存状态(或使用副本,或者想要构建代码)时进行分配。
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";
}
输出:
266666648
1113235983
1006007037
1572197236
322379391
Making Copy
1241299006
1359151196
1840219852
755708724
110209057
----
1241299006
1359151196
1840219852
755708724
110209057