Reyneer Leon Reyneer Leon - 4 months ago 16
C++ Question

How to create random function in Microsoft VS

I'm very new in Visual Studio so I dont know how to make a random function. I've been using Borland all the time. In borland it works well this method:

randomize();
int n=random(10);


Visual Studio gives me error using randomize function, I tried using
rand();
like this:

rand();
int n=random(10);


It isn't working, anyone can help me? ( I tried to find this problem here in stackoverflow and didn't get the solution, I don't think this is duplicated)

Answer

Using the standard library you can do something like this:

#include <random>
#include <iostream>

int main()
{
    // Mersenne Twister Pseudo Random Generator
    std::mt19937 gen{std::random_device{}()};

    // Random number range (inclusive)
    std::uniform_int_distribution<> pick{0, 9};

    for(int i = 0; i < 10; ++i)
        std::cout << pick(gen) << ' ';
}

Output:

0 7 0 2 1 2 6 9 8 1 
Comments