samedi 26 septembre 2020

Segmentation fault while working with 2D vectors

May I know exactly why my code is getting segmentation faults whenever I start traversing or taking input into the 2D vector? I don't understand what is causing the problem.

Edit: The myvect[ans].push_back is the part that's creating the problem.

So my question is why doesn't it just push back and create a vector at the myvect[ans] position? Isn't that what a dynamic vector is supposed to do? This is my code:

vector<vector<int>> myvect;
int ans = 2;

for(int i = 0; i < n; i++)
{
     myvect[ans].push_back(i+1);
     ans++;
}

for(int i = 0; i < myvect.size(); i++)
{
        if(!myvect[i].empty())
        {
            for(auto x: myvect[i])
                cout<<x<<" ";
        }
 }

Aucun commentaire:

Enregistrer un commentaire