0
#include<iostream>
#include<vector>
#include<bits/stdc++.h>
using namespace std;

int main(){
vector< set< int > > A;
A[0].insert(1);
A[0].insert(2);
}

When i run above ode on Codeblocks ,I get segmentation fault.Can anyone answer why am i getting this error and solution to avoid segmentation fault in this code.

  • 2
    `#include` don't do that! – Paul Rooney Nov 29 '17 at 03:50
  • 1
    First of all, please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Some programmer dude Nov 29 '17 at 03:51
  • 2
    Secondly, when you create your vector, it is *empty!*. All indexing will be out of bounds. Perhaps you need to take a step back, [get a couple of good beginners books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and start over? – Some programmer dude Nov 29 '17 at 03:52

2 Answers2

5

Since A is an empty vector, A[0] does not refer to a valid object. So you shouldn't be calling insert on it.

David Schwartz
  • 166,415
  • 16
  • 184
  • 259
1

the Vector A , is empty before you invoke it, so it is illegal to invoke A[0] ; insert something before .

Diglp
  • 11
  • 2