为什么向量下标超出范围

时间:2015-11-11 16:58:31

标签: c++ vector

我有一个充满怪物对象的矢量,它被初始化到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;
}

初始化功能

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只是检查一旦它运行它是否正常工作,箭头指示问题行。 感谢

2 个答案:

答案 0 :(得分:1)

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>

问题已经存在,载体中没有足够元素的路径。再加上if中的分配和比较的错误,比如已经提到的@Michael Waltz。

答案 1 :(得分:0)

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