Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我会出现超出范围的错误?_C++_Class_Object_Vector_Srand - Fatal编程技术网

C++ 为什么我会出现超出范围的错误?

C++ 为什么我会出现超出范围的错误?,c++,class,object,vector,srand,C++,Class,Object,Vector,Srand,我似乎找不到我的问题所在。它是一个三文件程序,一个文件中包含aDie类,另一个文件中包含aHistogram类,还有main.cpp文件。它应该打印一个由X构成的柱状图,以显示模具落在六个面上的次数。由于矢量错误,我无法前进。。。这个程序可能还有其他问题我还没有解决,但我只想知道向量误差。多谢各位 main.cpp: #include <iostream> #include <stdlib.h> //srand and rand #include <time.h&g

我似乎找不到我的问题所在。它是一个三文件程序,一个文件中包含aDie类,另一个文件中包含aHistogram类,还有main.cpp文件。它应该打印一个由X构成的柱状图,以显示模具落在六个面上的次数。由于矢量错误,我无法前进。。。这个程序可能还有其他问题我还没有解决,但我只想知道向量误差。多谢各位

main.cpp:

#include <iostream>
#include <stdlib.h> //srand and rand
#include <time.h> //Time
#include <vector>
#include <algorithm>
#include "aHistogram.h"
#include "aDie.h"

using namespace std;

int main()
{
    srand (time(NULL));
    int numRolls;
    const int maxLengthOfLine = 50;

    cout << "How many rolls? " << endl;
    cin >> numRolls;

    aDie fairDie;
    aHistogram fairHistogram;

    //For Loop rolls the die and updates the histogram vector ~~binHistogram.
    for(int i = 0; i < numRolls; i++)
    {
        int face = fairDie.roll();
        fairHistogram.update(face);
    }

    cout << "*******************" << endl;
    cout << "*****Histogram*****" << endl;
    cout << "*******************" << endl;

    fairHistogram.display(maxLengthOfLine);


}
#包括
#包括//srand和rand
#包括//时间
#包括
#包括
#包括“aHistogram.h”
#包括“aDie.h”
使用名称空间std;
int main()
{
srand(时间(空));
国际货币基金组织;
常量int maxLengthOfLine=50;
coutnumrolls;
阿迪·费尔迪;
非直方图;
//For Loop滚动模具并更新直方图向量~~ binHistogram。
对于(int i=0;icout我没有找到初始化直方图的位置,这可能是问题所在。但即使修复了它,您也会遇到另外两个错误:

for (int i = 1; i < numFaces; i++)
{
    while (binHistogram[i] >= largeBin)
    {
        largeBin = binHistogram.at(i);
    }
}

哪一行最有可能是导致错误的那一行(上面的那一行不会很好地告诉您问题出在哪里,只会使您的程序崩溃)。

aHistogram
类中,您永远不会更改向量的大小,这意味着它的大小将始终为零。任何索引都将超出范围

对于柱状图之类的东西,我实际上建议您使用而不是
std::vector
,其中“face”是键,count是数据

binHistogramMap[face] += 1;

不用担心
face
的元素不存在(如果条目不存在,它将被创建并初始化为零).

您使用的是
对象
srand
,但您的问题与这些标记无关,因此我尝试使用
private:const int numFaces=6;vector binHistogram(6)初始化向量;int totalRolls;int largeBin;double xScale;
因此我尝试使用
private:const int numFaces=6;vector binHistogram(6)初始化向量;int totalRolls;int largeBin;double xScale;
在Asistogram类的定义中。当我这样做时,我会得到预期的错误,或者…在数字常量之前为什么会这样。我已经在谷歌上搜索了数小时。@MaxMaurente你不能这样做,你必须使用。
for (int i = 1; i < numFaces; i++)
{
    while (binHistogram[i] >= largeBin)
    {
        largeBin = binHistogram.at(i);
    }
}
largeBin = binHistogram.at(i);
binHistogramMap[face] += 1;