我一直在尋找一個解決方案,我似乎正在修復一切與他們的錯誤,但我的仍然無法正常工作。C++調試斷言失敗。矢量下標超出範圍
以下代碼顯示了一個名爲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;
}
}
}
}
當i == v.size()-1時,'v [i + 1]'無效# –