C++ 为什么向量下标超出范围

C++ 为什么向量下标超出范围,c++,vector,C++,Vector,我有一个充满怪物对象的向量,它被初始化到一个10X10的地图上,这个地图可以工作。我现在正在玩一些代码来防止怪物在同一地图坐标上繁殖。当我运行代码时,它会剪切并显示“向量下标超出范围”,我不知道为什么。任何帮助都会很好 主要功能 #include "stdafx.h" #include "character.h" #include "monster.h" #include "player.h" #include <iostream> #include <ctime> #i

我有一个充满怪物对象的向量,它被初始化到一个10X10的地图上,这个地图可以工作。我现在正在玩一些代码来防止怪物在同一地图坐标上繁殖。当我运行代码时,它会剪切并显示“向量下标超出范围”,我不知道为什么。任何帮助都会很好

主要功能

#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;
}
#包括“stdafx.h”
#包括“character.h”
#包括“monster.h”
#包括“player.h”
#包括
#包括
#包括
#包括
使用名称空间std;
载体monVec;
向量monx;
向量mony;
玩家1;
布尔碰撞();
无效初始化();
int main(){
初始化();
player1.moveChar(3,6);
低温;
温度=碰撞();
系统(“暂停”);
返回0;
}
初始化函数

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;
    }
}
void initialize()
{
srand(时间(空));
对于(int n=0;n<10;n++)
{
int inx=rand()%9;
int iny=rand()%9;
如果(n==0){
monx。推回(inx);
一、推回(iny);
}
对于(int i=0;iif(inx!=monx[i]&&iny!=mony[i]){
monx。推回(inx);
一、推回(iny);
}
否则n--;
}
推回(新怪物());
monVec[n]->moveChar(inx,iny);
cout
void initialize()
{
srand(时间(空));
对于(int n=0;n<10;n++)
{
int inx=rand()%9;
int iny=rand()%9;

如果(n=0){/在
中初始化

您可以执行以下操作

<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>

//但向量只能保证每个向量至少有一个元素

问题已经是有一条路径在向量中没有足够的元素。加上你的
if
中关于赋值和比较的错误,比如@Michael Waltz已经提到过。

你怎么知道monx和mony有10个元素?看起来在你访问非循环之前,每个元素只有1个推回-现有矢量元素。因为最初有10个怪物产生,然后在N个回合后又增加了更多。ProXicT你能详细说明一下吗?@anon这段代码似乎在很多方面都有无可救药的缺陷。我认为未来任何研究都没有价值来解决这个问题。你应该用调试器检查你的程序,找出这些错误行为的原因。我明白你的意思了,我把(i<10)换成了(ibool check\u monster\u present(…)
。还要确保您对代码的假设是正确的,方法是使用
断言检查假设的内容。如果不确定元素是否存在,也可以使用
std::vector::at
而不是subscript/
[]
操作符。谢谢,我将从这里开始调试
<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>