C ++ Debug断言失败。矢量下标超出范围

时间:2016-03-05 01:24:37

标签: c++ function class loops vector

我一直在寻找解决方案,而且我似乎正在修复他们错误的一切,但是我的工作仍然无法解决。

以下代码显示了一个名为Creature的类的向量,对向量进行排序,然后显示已排序的向量。

    // displaying the unsorted vector
for (int i = 0; i < MAX_NO_CREATURES; i++)
{
    if (creatures[i].getAlive() != 0) // checking to see if a creature exists
    {
        for (unsigned int j = 0; j < creatures[i].getAvaFood().size(); j++)
        {
            cout << creatures[i].getAvaFood()[j] << " ";
        }
    }
}

//sorting the vector
for (int i = 0; i < MAX_NO_CREATURES; i++) 
{
    if (creatures[i].getAlive() != 0) // checking to see if a creature exists
    {
        creatures[i].bubbleSort(creatures[i].getAvaFood()); // calling a sorting function from creatures[i] passing in the relevant vector (its own.. wait what?)
    }
}

cout << endl;

// displaying the sorted vector
for (int i = 0; i < MAX_NO_CREATURES; i++)
{
    if (creatures[i].getAlive() != 0) // checking to see if a creature exists
    {
        for (unsigned int x = 0; x < creatures[i].getAvaFood().size(); x++)
        {
            cout << creatures[i].getAvaFood()[x] << " ";
        }
    }
}

当我点击错误窗口上的重试时,visual basic将我带到了生物类中的这一行。特别是IF声明。

void Creature::bubbleSort(vector<int> &v)
{
    bool swapped = true;
    int temp;
    while (swapped)
    {
        swapped = false;
        for (unsigned int i = 0; i < v.size(); i++)
        {
            if (v[i] > v[i + 1])
            {
                temp = v[i];
                v[i] = v[i + 1];
                v[i + 1] = temp;
                swapped = true;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

    for (unsigned int i = 0; i < v.size(); i++)
    {
        if (v[i] > v[i + 1])

for允许i为所有值[0,v.size],这意味着您将测试无效的v [v.size]。

将for循环更改为

    for (unsigned int i = 0; i < v.size() - 1; i++)

您需要添加一个v.size()不为零的检查。