random_discrete_distribution

random_discrete_distribution (이산 분포)

std::discrete_distribution은 구간 [0, n)에서 임의의 정수를 생성하는 분포 클래스예요. 각 정수 i의 확률은 wᵢ/S로 정의돼요. 즉 i번째 정수의 가중치를 모든 n개의 가중치의 합으로 나눈 값이에요. C++11부터 사용할 수 있어요.

출처: cppreference

본문

<random> 헤더에 정의되어 있고, 시그니처는 다음과 같아요.

template< class IntType = int >
class discrete_distribution;

(since C++11)

std::discrete_distribution은 구간 [0, n)에서 임의의 정수를 생성해요. 각 개별 정수 i의 확률은 wᵢ/S로 정의되는데, i번째 정수의 가중치를 모든 n개의 가중치의 합으로 나눈 값이에요.

std::discrete_distribution은 RandomNumberDistribution의 모든 요구사항을 만족해요.

템플릿 매개변수 (Template parameters)

  • IntType — 결과 타입. short, int, long, long long, unsigned short, unsigned int, unsigned long, unsigned long long 중 하나가 아니면 효과는 정의되지 않아요.

멤버 타입 (Member types)

멤버 타입 정의
result_type (C++11) IntType
param_type 매개변수 집합의 타입

멤버 함수 (Member functions)

  • (constructor) — 새 분포 생성
  • reset — 내부 상태 재설정
  • 생성: operator() — 다음 난수 생성
  • 특성: probabilities — 확률 목록 획득; param — 매개변수 객체 얻기/설정; min — 최솟값; max — 최댓값

비멤버 함수 (Non-member functions)

  • operator== operator!= — 두 분포 객체 비교
  • operator<< operator>> (C++11) — 스트림 입출력

예제 (Example)

이 코드를 실행해 봐요.

#include <iostream>
#include <map>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    // 가중치 {1, 2, 3, 4}
    std::discrete_distribution<> d({1, 2, 3, 4});

    std::map<int, int> hist;
    for (int n = 0; n != 10000; ++n)
        ++hist[d(gen)];

    for (auto [x, count] : hist)
        std::cout << x << ": " << count << '\n';
}

더 알아보기 (Learn more)

cppreference