Discrete distribution

Jul 9, 2015 at 5:55pm
Hello,

I am trying to implement the example found here:

http://www.cplusplus.com/reference/random/discrete_distribution/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  // discrete_distribution
#include <iostream>
#include <random>

int main()
{
  const int nrolls = 10000; // number of experiments
  const int nstars = 100;   // maximum number of stars to distribute

  std::default_random_engine generator;
  std::discrete_distribution<int> distribution {2,2,1,1,2,2,1,1,2,2};

  int p[10]={};

  for (int i=0; i<nrolls; ++i) {
    int number = distribution(generator);
    ++p[number];
  }

  std::cout << "a discrete_distribution:" << std::endl;
  for (int i=0; i<10; ++i)
    std::cout << i << ": " << std::string(p[i]*nstars/nrolls,'*') << std::endl;

  return 0;
}


But it does not compile. This is the first error I get for line 11:

error C2601: 'distribution' : local function definitions are illegal

Thank you!
Jul 9, 2015 at 6:04pm
Are you sure that your compiler is set to work with C++11 standard?
Jul 9, 2015 at 6:36pm
Add #include <string>

And if an old version of the Microsoft compiler is used, try inserting an = in line 11
1
2
// std::discrete_distribution<int> distribution {2,2,1,1,2,2,1,1,2,2};
std::discrete_distribution<int> distribution = {2,2,1,1,2,2,1,1,2,2};

Jul 9, 2015 at 6:42pm
Not sure. I am using Visual Studio 2012.
Jul 9, 2015 at 6:52pm
I already had #include <string>, and inserting the "=" still gives an error. Thank you, though!
Jul 9, 2015 at 6:52pm
Visual studio 2012 is marked as not supporting initializer lists: https://msdn.microsoft.com/en-us/library/hh567368.aspx

You can store probabilities in container and use iterator constructor:
1
2
3
  const int prob_size = 10;
  int probabilities[prob_size] = {2,2,1,1,2,2,1,1,2,2};
  std::discrete_distribution<int> distribution(probabilities, probabilities + prob_size);
Jul 9, 2015 at 7:05pm
Thank you!

This now gives an error for the third line in your code: error C2661: 'std::discrete_distribution<_Ty>::discrete_distribution' : no overloaded function takes 2 arguments
Jul 9, 2015 at 7:19pm
It appears that VS2012 missing iterator constructor as well...
Well, only way to initialize it is to use last consructor and ugly hack (I hope at least lambdas are properly supported):
1
2
3
4
  std::discrete_distribution<int> distribution(10, 0, 10,
                                               [](double d)
                                               {static const int prob[] = {2,2,1,1,2,2,1,1,2,2};
                                                return prob[static_cast<size_t>(d)];});

EDIT: I suggest to update your compiler too. Either 2015 RC, or 2013 would be fine: http://www.cplusplus.com/forum/lounge/169021/
Last edited on Jul 9, 2015 at 7:21pm
Jul 9, 2015 at 7:23pm
This worked. Thank you very much!
Topic archived. No new replies allowed.