[英]why is vector subscript out of range
I have a vector full of monster objects which are initialized onto a 10X10 map which works.我有一个充满怪物对象的向量,它们被初始化到一个可以工作的 10X10 地图上。 I am now playing with some code to prevent monsters being spawned on the same map co-ordinate.
我现在正在使用一些代码来防止怪物在同一地图坐标上产生。 when i run the code it cuts and brings up "vector subscript out of range" and i have no idea why.
当我运行代码时,它会剪切并显示“向量下标超出范围”,我不知道为什么。 Any help would be great.
任何帮助都会很棒。
main function主功能
#include "stdafx.h"
#include "character.h"
#include "monster.h"
#include "player.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
vector<monster*> monVec;
vector<int> monx;
vector<int> mony;
player player1;
bool collision();
void initialise();
int main(){
initialise();
player1.moveChar(3, 6);
bool temp;
temp = collision();
system("pause");
return 0;
}
initialize function初始化函数
void initialize()
{
srand(time(NULL));
for (int n = 0; n < 10; n++)
{
int inx = rand() % 9;
int iny = rand() % 9;
if (n == 0){
monx.push_back(inx);
mony.push_back(iny);
}
for (int i = 0; i < n; i++)
{
-------->if (inx != monx[i] && iny != mony[i]){
monx.push_back(inx);
mony.push_back(iny);
}
else n--;
}
monVec.push_back(new monster());
monVec[n]->moveChar(inx, iny);
cout << endl << inx << ", " << iny << endl;
}
}
cout is just to check if its working once it runs and arrow indicates problem line. cout 只是检查它运行后是否正常工作,箭头指示问题线。 thanks
谢谢
In your initialize
you do the following在您的
initialize
您执行以下操作
<for 10 times>
<when first time, add one item to the x,y vectors>
<access the up to 10nth element of the x,y vectors> //But vectors are only guaranteed to have at least one element each
<maybe add one item to the x,y vectors>
Problem is already that there is a path where there are not enough elements in your vectors.问题是已经有一条路径,其中您的向量中没有足够的元素。 Plus the mistake about assignment and comparison in your
if
like @Michael Waltz already mentioned.加上你的
if
like @Michael Waltz 已经提到的关于分配和比较的错误。
void initialize()
{
srand(time(NULL));
for (int n = 0; n < 10; n++)
{
int inx = rand() % 9;
int iny = rand() % 9;
if (n = 0){ //<<--------------------------- replace (n = 0) by (n == 0)
monx.push_back(inx);
mony.push_back(iny);
}
for (int i = 0; i < 10; i++)
{
// <<<< here monx and mony may contain only
// one element so monx[1] and mony[1] are invalid
if (inx != monx[i] && iny != mony[i]){
monx.push_back(inx);
mony.push_back(iny);
}
else n--;
}
monVec.push_back(new monster());
monVec[n]->moveChar(inx, iny);
cout << endl << inx << ", " << iny << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.