首页 > 解决方案 > 带有调试错误的简单老虎机 C++

问题描述

我正在尝试创建一个简单的老虎机,它使用三个矢量,一个用于左、右和中心卷轴。对于此代码,我收到调试错误“向量下标超出范围”,但不知道为什么。我要做的就是获取向量或卷轴,在每个向量中选择一个随机元素,然后打印出随机选择的元素之后的下两个数字。在我调用自旋函数之后,一旦程序崩溃。

void spin(vector<int> lReel, vector<int> cReel, vector<int> rReel)
{
int random = rand() % lReel.size();
int lselection1 = lReel[random];
int lselection2 = lReel[random + 1];
int lselection3 = lReel[random + 2];

cout << lselection1 << " " << lselection2 << " " << lselection3 << endl;

int random2 = rand() % cReel.size();
int cselection1 = cReel[random2];
int cselection2 = cReel[random2 + 1];
int cselection3 = cReel[random2 + 2];

cout << cselection1 << " " << cselection2 << " " << cselection3 << endl;

int random3 = rand() % rReel.size();
int rselection1 = rReel[random3];
int rselection2 = rReel[random3 + 1];
int rselection3 = rReel[random3 + 2];

cout << rselection1 << " " << rselection2 << " " << rselection3 << endl;

}
int main()
{
vector<int> Left_Reel{ 1, 2, 3, 4, 5, 2, 2, 3, 4, 2, 2, 1, 1, 3, 3, 4, 2, 1, 1, 1, 4, 
3, 2, 2, 1 };
vector<int> Center_Reel{ 3, 1, 2, 2, 3, 3, 4, 4, 2, 2, 3, 2, 1, 2, 4, 3, 2, 2, 1, 5, 4, 
1, 3, 2, 2 };
vector<int> Right_Reel{ 2, 3, 4, 4, 4, 3, 1, 1, 1, 2, 3, 5, 4, 3, 2, 2, 2, 1, 1, 1, 3, 
2, 1, 1, 2 };

cout << "SPIN" << endl;
spin(Left_Reel, Center_Reel, Right_Reel);
cout << "SPIN" << endl;
spin(Left_Reel, Center_Reel, Right_Reel);

system("Pause");
return 0;
}

标签: c++

解决方案


问题在这里:

int random = rand() % lReel.size();
int lselection1 = lReel[random];
int lselection2 = lReel[random + 1];
int lselection3 = lReel[random + 2];

当您选择 random 时,它可以是0to的值size-1,因此如果 random = to size - 2 或 size - 1 您将溢出缓冲区并读取可能会使您的应用程序崩溃的未初始化内存。

一个快速修复可以是这个:

int random = rand() % lReel.size();
int lselection1 = lReel[random];
int lselection2 = lReel[(random + 1) % lReel.size()];
int lselection3 = lReel[(random + 2) % lReel.size()];

因此您将修复对未初始化内存的访问。我还建议使用 srand 初始化伪随机数生成器,否则您将始终得到相同的序列。

srand (time(NULL));

推荐阅读