Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>Why <code>rand</code> is a bad idea</h2> <p>Most of the answers you got here make use of the <code>rand</code> function and the modulus operator. That method <a href="http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful">may not generate numbers uniformly</a> (it depends on the range and the value of <code>RAND_MAX</code>), and is therefore discouraged.</p> <h2>C++11 and generation over a range</h2> <p>With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: <a href="http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution"><code>std::uniform_int_distribution</code></a>. Here's an example:</p> <pre><code>const int range_from = 0; const int range_to = 10; std::random_device rand_dev; std::mt19937 generator(rand_dev()); std::uniform_int_distribution&lt;int&gt; distr(range_from, range_to); std::cout &lt;&lt; distr(generator) &lt;&lt; '\n'; </code></pre> <p>And <a href="http://coliru.stacked-crooked.com/a/c5b94870fdcd13f2">here</a>'s the running example.</p> <h3>Other random generators</h3> <p>The <a href="http://en.cppreference.com/w/cpp/numeric/random"><code>&lt;random&gt;</code> header</a> offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.</p> <h3>How can I shuffle a container?</h3> <p>The standard provides <a href="http://en.cppreference.com/w/cpp/algorithm/random_shuffle"><code>std::random_shuffle</code></a>, which can be used as follows:</p> <pre><code>std::vector&lt;int&gt; vec = {4, 8, 15, 16, 23, 42}; std::random_device random_dev; std::mt19937 generator(random_dev()); std::shuffle(vec.begin(), vec.end(), generator); </code></pre> <p>The algorithm will reorder the elements randomly, with a linear complexity.</p> <h2>Boost.Random</h2> <p>Another alternative, in case you don't have access to a C++11+ compiler, is to use <a href="http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random.html">Boost.Random</a>. Its interface is very similar to the C++11 one.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload