为什么我不断收到二维矢量的“矢量下标超出范围”错误?

问题描述

我正在尝试使用向量 (v) 的向量 (V) 创建邻接列表图表示。我的目标是对于输入的每个新顶点值,我增加 V* 的大小,并将新值插入到开放点中,这将成为 v** 的起始值。

然后我想在输入的新值和邻接矩阵中已经存在的另一个值之间创建一条边。

但是,使用我的代码,一旦我输入 secIndexVal,我就会不断收到“向量下标超出范围错误”。我已经尝试使 numberIndices 的初始值更大(最多 10)以及我在代码中提到的内容。谢谢。

*向量的向量,我记为“V” ** V 内的向量,我记为 'v'

int indexVal; 
int secIndexVal; 
int numberIndices = 0; 
bool valIsFound = false; 
vector <vector <int>> vecOfVectors(numberIndices);

int main()
{
    cout << "\nEnter first value: ";
    cin >> indexVal;

    cout << "\nEnter second value: ";
    cin >> secIndexVal;

    numberIndices++;
    vecOfVectors.resize(numberIndices);
    vecOfVectors[numberIndices - 1].push_back(indexVal);
    vecOfVectors[numberIndices - 1].push_back(secIndexVal);
    //pushes back the values of indexVal then secIndexVal to index 0 
    //I tried changing the value within the brackets to [numberIndices]

    numberIndices++;
    vecOfVectors.resize(numberIndices);
    vecOfVectors[numberIndices].push_back(secIndexVal); 
    vecOfVectors[numberIndices].push_back(indexVal);
    //pushes back the values of secIndexVal then indexVal to index 1
    //I tried changing the value within the brackets to [numberIndices + 1]         

    cout << "\nExit? (y/n)";
    cin >> userPrompt;

    while (userPrompt != 'y')
    {

        cout << "\nEnter a new value: ";
        cin >> indexVal; //new value

        numberIndices++;
        vecOfVectors.resize(numberIndices); 

        cout << "\n enter a value to connect it to: ";
        cin >> secIndexVal; //old value

        vecOfVectors[numberIndices - 1].push_back(indexVal); //new value given newly opened spot on vecOfVectors


        for (int j = 0; j < numberIndices; ++j)
        {
            if (vecOfVectors[j].at(0) == secIndexVal)
            {
                valIsFound = true; 
                vecOfVectors[j].push_back(indexVal); //the new value is attached to the adjacency list at the index of the old value
            }
        }

        if (valIsFound == true)
        {
            vecOfVectors[numberIndices - 1].push_back(secIndexVal); //the old value is attached to the adjacency list at the index of the new value
        }

        cout << "\nExit? (y/n)";
        cin >> userPrompt;
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)