Restrict random number generation to a range using <random>

776 Views Asked by At

I'm generating random numbers in C++11. When I run my code

using namespace std;

static std::mt19937_64 rng;

int main() {
rng.seed(11);

    std::cout << rng() << std::endl;
}

It returns random numbers. However, I would like to restrict this to a range of numbers, say 1-1000. How would I do this, using the new <random> file/library introduced in C++11?

1

There are 1 best solutions below

9
Rapptz On BEST ANSWER

Use std::uniform_int_distribution from <random>.

Example:

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dis(1, 1000);

    std::cout << dis(gen) << '\n';
}

The <random> header includes a lot of other distributions that you can use. You can check it out here