Home > Back-end >  Debug Assertion Failed: Expression vector subscript out of range
Debug Assertion Failed: Expression vector subscript out of range

Time:05-16

I dont understand why it says subscript out of range when I have reserved the space in the vector. I have created a short form of my code to explain what the problem is better:

#include <vector>
#include <string>
#include <thread>
#include <iostream>

using namespace std;

class A {
public:
    vector<vector<string>> foo;
    thread* aThread;

    A() {
        foo.reserve(10); //makes sure we have space...
        aThread = new thread([this]() {
            for (int i = 0; i < 10; i  ) {
                foo[i].push_back("Hello"); // Debug assertion failed. :(
            }
        });
    }
};

int main()
{
    A a;
    a.aThread->join();

    for (int i = 0; i < 10; i  ) {
        for (int j = 0; j < a.foo.size(); j  ) {
            cout << a.foo[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Here it gives the error as soon as I am trying to add the element into my foo vector inside the thread. I cannot figure out what is wrong. Please help.

CodePudding user response:

foo.reserve(10)

Reserves space for elements in foo, but it does not populate any of the elements with an empty std::vector.

You can change it to:

foo.resize(10);

Which will reserve the space and create the empty vector< string > elements, so that you can access them.

  • Related