-2

Why am I getting segmentation fault in this piece of code?

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


int main()
{
    vector<vector<string> > v;
    v[0].push_back("good");
    
    cout<<v[0][0];

}

I am trying to insert the string "good" in the first vector, and I am trying to access that by v[0][0], but it is giving me segmentation fault. Please help. Thanks.

Turing101
  • 347
  • 3
  • 15
  • 1
    You vector is empty. `v[0]` doesn't exist. – dandan78 May 26 '21 at 16:26
  • 1
    Obligatory avoid `using namespace std;` ([why](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)) and do not use `#include` ([why](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)) comment. Separately they are bad, but when you put them together, they magnify each other's worst effects and turn the program into a minefield of unused identifiers. – user4581301 May 26 '21 at 16:41

1 Answers1

1

The inner vector starts out with 0 elements, you push 1 element and then you can access the first via [0]. That's fine.

However, the outer vector works the same way: You first need to add an element before you can access it.

Either call the constructor that lets you specify the size:

vector<vector<string> > v(1);
v[0].push_back("good");

or push the element:

vector<vector<string> > v;
vector<string> w;
w.push_back("good");
v.push_back(w);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185