You seek a method to uniformly generate random numbers within a specified range [min, max].
Flaws with rand
Your current implementation using rand() and the modulus operator may not ensure uniform distribution, as its behavior depends on RAND_MAX and the range itself.
C 11 and Uniform Range Generation
In C 11, std::uniform_int_distribution offers a solution tailored to this need:
#includestd::uniform_int_distribution distr(min, max); std::random_device rand_dev; std::mt19937 generator(rand_dev()); int random_number = distr(generator);
Additional Features of
The
Container Shuffling
To shuffle a container, employ std::shuffle:
#include#include std::vector vec = {4, 8, 15, 16, 23, 42}; std::random_device random_dev; std::mt19937 generator(random_dev()); std::shuffle(vec.begin(), vec.end(), generator);
Boost.Random
If using a C 11 compiler is not feasible, consider Boost.Random, which features a similar interface to the C 11 counterpart.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3