Why do I keep getting "vector subscript out of range" error for 2D vector?

I am trying to create an adjacency list graph representation using a vector(V) of vectors(v). My goal is for every new vertex value entered, I increment the size of the V*, and insert the new value into the open spot, which would then be the starting value of v**.

I then want to create an edge between the new value entered, and another value that already exists in the adjacency matrix.

However, with my code I keep getting the "vector subscript out of range error" once I enter the secIndexVal. I’ve already tried making the initial value of numberIndices larger (up to 10) as well as the things I’ve mentioned in the code. Thank you.

*The Vector of vectors, I notated as ‘V’
**A vector within V, I notated as ‘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;
    }
}

Source: Windows Questions C++

LEAVE A COMMENT