Skip to content

Std::random

std::random_device

Example

#include <random>
#include <ctime>
#include <iostream>
#include <functional>

using namespace std;

int main()
{
    mt19937 engine((unsigned int)time(NULL));                    // MT19937 난수 엔진
    uniform_int_distribution<int> distribution(0, 100);       // 생성 범위
    auto generator = bind(distribution, engine);

    // 0~100 범위의 난수 100개 생성하여 출력
    for (int i = 0; i < 100; ++i)
        cout << generator() << endl;
}

또는 아래와 같이 함수를 만들 수 있다.

#include <random>
#include <type_traits>

template <typename Integer>
static Integer gen(Integer min, Integer max) {
    static_assert(std::is_integral<Integer>::value, "This is not an integer type.");
    std::random_device device;
    std::mt19937 engine(device());
    std::uniform_int_distribution<Integer> distribution(min, max);
    return distribution(engine);
}

See also

Favorite site