Hello! I am currently coding a little console game in C++, and in my game I have features that requires randint to be functional. For a long time, I was using #include <experimental/random> and it worked! Then, I decided to switch my IDE to Visual Studio Code, and suddenly experimental/random no longer existed and randint didn't work. The IDE I was using previously was Sublime Text. I tried to switch back to Sublime Text but it still wasn't working. How can I fix this problem? Is there a way I can download experimental/random and make it work again? Any help is appreciated! Thanks!
Most likely you updated the compiler and the new version doesn't have <experimental/random> anymore. <experimental/*> headers are not meant to be used in productive code, they're meant as a demo of future capabilities. The implementation developers may remove such headers at any time.
Are you using threads? If not then just create a global generator and seed it when your program starts.
1 2 3 4 5
std::mt19937 rng;
int randint(int from, int to){
return std::uniform_int_distribution<int>(from, to)(rng);
}
randint and the experimental header would be replaced with:
1. include <random> (and <chrono> if you want a C++ time seed)
2. instantiate a random number engine object
3. instantiate a distribution object, uniform_int_distribution would be a good fit.
4. generate your random number by calling the distribution object with the RNG as the input.
#include <iostream>
#include <chrono>
#include <random>
int main()
{
// get a seed based on the system clock
unsigned seed { static_cast<unsigned> (std::chrono::system_clock::now().time_since_epoch().count()) };
// create a pseudo random number engine, seeding it with the time from earlier
std::default_random_engine prng(seed);
// create a distribution
std::uniform_int_distribution<int> dist(1, 25);
// let's generate some random numbers
for (unsigned i { 1 }; i <= 25; i++)
{
std::cout << dist(prng) << ' ';
if (!(i % 10))
{
std::cout << '\n';
}
}
std::cout << '\n';
}
A bit complicated, but C++ random number generation has a wide variety of options when generating numbers, integral and real numbers.
If you don't need a lot of random numbers AND your compiler supports it you could use std::random_device:
#include <iostream>
#include <random>
int main()
{
// create a true random number engine, no need to seed
std::random_device prng;
// create a distribution
std::uniform_int_distribution<int> dist(1, 25);
// let's generate some random numbers
for (unsigned i { 1 }; i <= 25; i++)
{
std::cout << dist(prng) << ' ';
if (!(i % 10))
{
std::cout << '\n';
}
}
std::cout << '\n';
}
Has sample code for creating a random number toolkit. Drop it into a custom header file so you aren't trying to reinvent the wheel each time you need random numbers.