Search code examples
c++vectorstd-pairpush-back

How to set up vector of vector pairs?


In this code, I am trying to make a vector of vector pairs. The code compiles but it has a segmentation fault and I cannot figure out where I am going wrong. I would be grateful for any hint that can solve my problem.

#include <iostream>
#include <vector>
using namespace std;
vector<vector<pair<int,bool> > > pairs; 

    void insert(int x, int y)
    {
      pair<int,bool> tuple=make_pair(y,0);
      pairs[x].push_back(tuple);
    }

    void pairing()
    {
       for(int i=0; i<12; i++)
       {
         for(int j=0; j<12; j++)
         {
           insert(i,j);
         }
       }
    }

    int main() 
    {
      pairing();
      return 0;   
    }

Solution

  • pairs has no elements so you can't do this: pairs[x].

    Either resize the pairs vector so it has N blank vector<pair<int,bool> > in it, or create a vector<pair<int,bool> > first and push it back into pairs