我想从[1,10]中多次抽取1个整数,然后检查每个整数出现了多少次。我写了这段代码,它正在编译但显示段错误。能否请您指出问题出在哪里?
#include <iostream>
#include <random>
#include <array>
int main(){
std::random_device rd;
std::mt19937 dre(rd());
std::uniform_int_distribution <int> di(1,10);
std::array<int,10> count{0};
for(int i=0;i<10000;++i)
{
int rand=di(dre);
count[rand]++;
}
for (int foo: count){
count[foo]/=10000;
std::cout << foo << " " << count[foo] << std::endl;
}
}
最佳答案
如果您定义一个由 10 个元素组成的数组,就像您在此处所做的那样:
std::array<int,10> count{0};
然后数组的索引为 0-9。所以 count
的范围从 count[0]
到 count[9]
。
但是,这里:
count[rand]++;
当 rand
为 10 时,您正在尝试访问不存在的 count [10]
。
为了回答您编辑中的后续问题,您将循环并创建 10000
随机数,此处:
for(int i=0;i<10000;++i)
{
int rand=di(dre);
当您在 10 个不同的数字之间进行选择时,您会期望每个数字的数量大约为 1000,并且呈均匀分布。
但是,当您打印结果时,您将每个计数除以 10000:
count[foo]/=10000;
所以这意味着每个计数现在很可能约为 0.1。当您将它存储在一个 int 中时,它会向下舍入为零。
关于c++ - 阵列访问期间的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951140/