c++ - "p"数组如何使用 C++ std::normal_distribution 在以下代码中存储值?

标签 c++ arrays pointers std normal-distribution

我正在尝试将高斯噪声添加到 vector 的元素中,因此我想在我的代码中使用 std::normal_distribution 模板。我正在查看此链接中的示例:Normal distribution example ,但我无法弄清楚 int p[10]={} 是如何编写的,我已经运行了代码并且似乎工作正常。

这是我无法理解的代码片段,p 似乎将值存储在这个 for 循环中:

 int p[10]={};

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

完整代码供引用:

// 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;
}

以及预期结果(与运行此代码后的输出相同):

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: *

最佳答案

int p[10]={}; 声明了一个包含 10 个 int 元素的数组,这些元素都被初始化为 0

++p[int(number)]; 为生成的 number 递增数组元素,该元素介于 0..9 之间,包括端值。

operator[] 有一个 higher precedence而不是前缀 operator++,因此首先评估 p[number] 以获取对数组中 int 的引用,然后是 ++ 递增 int

关于c++ - "p"数组如何使用 C++ std::normal_distribution 在以下代码中存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52395849/

相关文章:

c++ - 数组在循环中的行为

javascript - 根据不匹配某些值返回 JSON

arrays - Ruby 数组 += vs 推送

angularjs - Angular 2 : cannot read property 'push' of undefined

c++ - 节点指针内部的指针

c - 需要写入一个字符串常量,我该如何解决这个问题?

c++ - 在 IDE 之外构建 WM C++ 项目

c++ - 我正在使用命令提示符在 C++ 中做一个非常简单的应用程序

C++ double 值在相乘时丢失精度?

c++ - 通过引用 C 函数的参数