Mario Mario - 2 years ago 121
C++ Question

std::uniform_int_distribution<int> range in g++ and msvc

While doing a minor school project, I just noticed a difference in the
range of


When using g++ the range is [a, b], however when using msvc (Visual Studio 2010) the range is (a, b], so the output of the following program:

#include <iostream>
#include <random>

using std::cout;
using std::cin;

int main()
std::mt19937 random;
std::uniform_int_distribution<int> intDist(-1, 1);

for(int i = 0; i < 100; i++)
cout << intDist(random) << "\n";


Will display -1 at some point when using g++, but it will never display -1 when using msvc.

I know is common that such differences exists between compilers, but booth the MSDN documentation and the standard mark that the range should be [a, b].

What is the reason for this behavior?

Answer Source

It's a bug in the Visual Studio 2010 implementation of std::uniform_int_distribution.

I reported it here in December 2011 and got confirmation from Stephan T. Lavavej that:

  1. It is indeed a bug.
  2. It's been fixed in the next version of Visual Studio (including the current Developer Preview).

The bug occurs when the first parameter to the std::uniform_int_distribution constructor is negative. To work around it in your example, construct the distribution like this:

std::uniform_int_distribution<int> intDist(0, 2);

And then call it like this:

cout << intDist(random) - 1 << "\n";  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download