在[0,n)中生成随机

vla*_*don 1 c++ random c++11

使用<random>C++ 11的标准函数/类/等如何在这些范围内生成随机数:

  • (n,m) - 不包括两端
  • (n,m) - 不包括开头
  • [ n,m) - 不包括结束

特殊情况:

  • [0,n)
  • [0,1)

或者可能有任何文件,如备忘单<random>

Bil*_*nch 9

统一的实际分布

A uniform_real_distribution将给出范围内的值[a, b).我们可以std::nextafter用来在开放和闭合范围之间进行转换.

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());

    // [1, 10]
    std::uniform_real_distribution<> dist_a(1, std::nextafter(10, std::numeric_limits<double>::max));

    // [1, 10)
    std::uniform_real_distribution<> dist_b(1, 10);

    // (1, 10)
    std::uniform_real_distribution<> dist_c(std::nextafter(1, std::numeric_limits<double>::max), 10);

    // (1, 10]
    std::uniform_real_distribution<> dist_d(std::nextafter(1, std::numeric_limits<double>::max), std::nextafter(10, std::numeric_limits<double>::max));

    // Random Number Generators are used like this:
    for (int i=0; i<16; ++i)
        std::cout << dist_d(mt) << "\n";
}
Run Code Online (Sandbox Code Playgroud)

统一Int分布

A uniform_int_distribution将给出范围内的值[a, b].我们可以添加和减去1在打开和关闭范围之间切换.

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());

    // [1, 10]
    std::uniform_int_distribution<> dist_a(1, 10);    

    // [1, 10)
    std::uniform_int_distribution<> dist_b(1, 10 - 1); 

    // (1, 10)
    std::uniform_int_distribution<> dist_c(1 + 1, 10 - 1); 

    // (1, 10]
    std::uniform_int_distribution<> dist_d(1 + 1, 10);

    // Random Number Generators are used like this:
    for (int i=0; i<16; ++i)
        std::cout << dist_d(mt) << "\n";
}
Run Code Online (Sandbox Code Playgroud)