0

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;   
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user143
  • 19
  • 5
  • `std::vector>> pairs(12, {{0, false}, {1, false}, .., {10, false}, {11, false}});` (you probably want to create function to create inner vector). – Jarod42 Sep 08 '18 at 00:24
  • The vector `pairs` is created with size zero, and nothing in your code changes that. Evaluating `pairs[x]` therefore gives undefined behaviour for any value of `x`, as does doing any operation on it (i.e. `pairs[x].push_back(tuple)`). You need to resize `pairs` so it has enough elements before trying to manipluate the vectors it contains. – Peter Sep 08 '18 at 00:24

2 Answers2

0

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

Anon Mail
  • 4,660
  • 1
  • 18
  • 21
0

Reading the std::vector reference for operator []...

"Unlike std::map::operator[], this operator never inserts a new element into the container."

Madison A.
  • 13
  • 6