c++ - 带有调试错误的简单老虎机 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;
}
解决方案
问题在这里:
int random = rand() % lReel.size();
int lselection1 = lReel[random];
int lselection2 = lReel[random + 1];
int lselection3 = lReel[random + 2];
当您选择 random 时,它可以是0
to的值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));
推荐阅读
- javascript - 重定向到某个页面然后执行一个事件或动作
- python - 如何在 python 中使用 for 循环创建多个数据框
- sql-server - 输出具有多个属于不同项目组配置的销售项目的 SQL 单个事务
- c++ - 什么保证两个不相关线程中的不同不相关对象没有(不可避免的)竞争条件?
- java - 排序坐标系
- python - 如何使用 Cloudflare SSL 证书设置简单的 https 服务器?
- javascript - 滚动时顶部的粘性元素
- c# - RedirectToAction 不调用动作
- haskell - Why does the inliner choke on this construct?
- amazon-web-services - Aws Appsync 解析器:如何创建解析器以更新列表映射 (DynaMoDB) 中的项目