Search code examples
c++arrayspointersstdnormal-distribution

How the "p" array store the values in the following code using C++ std::normal_distribution?


I'm trying to add Gaussian noise to the elements of a vector and therefore I would like to use the std::normal_distribution template in my code. I was looking at an example at this link:Normal distribution example, but I can't figure out how int p[10]={} is being write, I have run the code and seems to be working fine.

Here is the code snippet that I can't figure out, p seems to be storing the values in this for loop:

 int p[10]={};

  for (int i=0; i<nrolls; ++i) {
    double number = distribution(generator);
    if ((number>=0.0)&&(number<10.0)) ++p[int(number)];
  }

Here is the complete code as reference:

// normal_distribution
#include <iostream>
#include <string>
#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::normal_distribution<double> distribution(5.0,2.0);

  int p[10]={};

  for (int i=0; i<nrolls; ++i) {
    double number = distribution(generator);
    if ((number>=0.0)&&(number<10.0)) ++p[int(number)];
  }

  std::cout << "normal_distribution (5.0,2.0):" << std::endl;

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

  return 0;
}

And the expected result (which it's the same output I have after running this code):

normal_distribution (5.0,2.0):
0-1: *
1-2: ****
2-3: *********
3-4: ***************
4-5: ******************
5-6: *******************
6-7: ***************
7-8: ********
8-9: ****
9-10: *

Solution

  • int p[10]={}; declares an array of 10 int elements that are all initialized to 0.

    ++p[int(number)]; increments an array element for a generated number that is between 0..9, inclusive.

    The operator[] has a higher precedence than the prefix operator++, so p[number] is evaluated first to get a reference to an int in the array, and then ++ increments that int.