-1

如何使用 marsenne twister 算法生成 32 位整数随机数?并将其保存为二进制文件。

4

1 回答 1

0
#include <algorithm>
#include <fstream>
#include <ios>
#include <iostream>
#include <iterator>
#include <ostream>
#include <random>
#include <vector>

int main()
{
    // Create the random number engine
    std::mt19937::result_type seed = std::random_device()();
    auto engine = std::mt19937(seed);
    auto random = [&engine]() { return engine(); };

    // Generate some random numbers
    auto constexpr n = 1000;
    auto numbers = std::vector<std::mt19937::result_type>();
    std::generate_n(std::back_inserter(numbers), n, random);

    // Write them out to a file
    auto fout = std::ofstream("random_numbers.bin", std::ios::binary);
    fout.write(reinterpret_cast<const char*>(numbers.data()), 
        n * sizeof(decltype(numbers)::value_type));

    return 0;
}
于 2019-11-25T11:26:54.003 回答