如何保存/检索MT19937,以便重复序列

How to save/retrieve mt19937 so that the sequence is repeated?

本文关键字:MT19937 检索 何保存 保存      更新时间:2023-10-16

这是我的尝试

using namespace std;
int main()
{
    mt19937 mt(time(0));
    cout << mt() << endl;
    cout << "----" << endl;
    std::ofstream ofs;
    ofs.open("/path/save", ios_base::app | ifstream::binary);
    ofs << mt;
    ofs.close();
    cout << mt() << endl;
    cout << "----" << endl;
    std::ifstream ifs;
    ifs.open("/path/save", ios::in | ifstream::binary);
    ifs >> mt;
    ifs.close();
    cout << mt() << endl;
    return 0;
}

这是可能的输出

1442642936
----
1503923883
----
3268552048

我希望最后两个数字相同。显然,我没有写和/或阅读我的MT19937。您可以帮助修复此代码吗?

打开文件写作时,您将附加到现有文件。当您重新阅读时,您会从一开始就阅读。

假设您不想保留现有内容,请将打开的呼叫更改为

ofs.open("/path/save", ios_base::trunc | ifstream::binary);

使用trunc标志而不是app将截断现有文件,因此,当您重新打开它时,您将在刚刚编写的数据中读取而不是已经存在的旧数据。