在C ++中获取均匀分布的随机整数的标准方法是什么? [英] What's the standard way for getting uniformly distributed random integers in C++?

查看:143
本文介绍了在C ++中获取均匀分布的随机整数的标准方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有在一定范围内获得均匀分布式伪随机整数的函数?我可以使用 rand 编写我自己的函数,但这似乎是一个常见的情况,在STL中可能有一些东西。

Is there a function for obtaining uniformly distributed pseudo-random integers in some specified range? I could write my own function using rand, but this seems like a common enough situation that there's probably something in the STL for it.

推荐答案

Boost 提供了许多随机数生成工具。
对于均匀分布,您有以下这个:

Boost provides many tools for random number generation. For uniform distributions you have this one:

http://www.boost.org/doc/libs/1_49_0/doc/html/boost/random/uniform_real_distribution.html

EDIT:更新为包含新的C ++ 11实现。对于整数的情况,这里你有引用:

updated to include the new C++11 implementation. For the case of integers, here you have the reference:

http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution

一个简单的例子是:

#include <random>
#include <iostream>
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);
    for(int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

这篇关于在C ++中获取均匀分布的随机整数的标准方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆