"p" 数组如何使用 C++ std::normal_distribution 存储以下代码中的值?
How the "p" array store the values in the following code using C++ std::normal_distribution?
我正在尝试将高斯噪声添加到向量的元素中,因此我想在我的代码中使用 std::normal_distribution 模板。我正在查看此 link: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[]
比前缀 operator++
有一个 higher precedence,因此首先计算 p[number]
以获得对数组中 int
的引用,然后 ++
增加 int
.
我正在尝试将高斯噪声添加到向量的元素中,因此我想在我的代码中使用 std::normal_distribution 模板。我正在查看此 link: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[]
比前缀 operator++
有一个 higher precedence,因此首先计算 p[number]
以获得对数组中 int
的引用,然后 ++
增加 int
.