<random> ライブラリを使ってみる (C++)
C++
Published: 2020-04-05

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

test.cpp

#include <bits/stdc++.h>
using namespace std;

int main() {
    std::random_device rng;
    for (int i = 0; i < 5; i++) {
        cout << rng() << endl;
    }
    cout << "---" << endl;
    std::mt19937 engine(rng());
    std::uniform_real_distribution<> dist1(-1.0, 1.0);
    for (int i = 0; i < 5; i++) {
        cout << dist1(engine) << endl;
    }

    cout << "-- 1 ~ 10 の整数を等確率で出力する --" << endl;
    std::random_device rng2;
    std::mt19937 engine2(rng2());
    std::uniform_int_distribution<> dist2(1, 10);
    for (int i = 0; i < 5; i++) {
        cout << dist2(engine2) << endl;
    }
}

出力結果

28733216
299212032
131005940
463750635
2721402783
---
-0.179933
-0.992599
-0.705688
-0.27019
-0.209114
-- int -
5
9
10
1
7

参考