-1

I havent done C++ in a while.

Im trying to get a vector of vectors to print data. I get the following error:

Segmentation fault (core dumped)

I am using an online complier to run the code.

#include <iostream>     // std::cout
#include <algorithm>    // std::for_each
#include <vector>       // std::vector

void myfunctiontwo (int i) {  // function:
  std::cout << ' ' << i;
}

void myfunction (std::vector<int> myvector) {  // function:
  for_each (myvector.begin(), myvector.end(), myfunctiontwo);
}

int main () {
  // create a vector of vectors. 
  std::vector< std::vector<int> > myvector; 

  // add some data
  myvector[0].push_back(10); 
  myvector[1].push_back(20);
  myvector[2].push_back(30);

  std::cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction);
  std::cout << '\n';

  return 0;
}
maffo
  • 1,393
  • 4
  • 18
  • 35

2 Answers2

3

Your problem is the pushing back:

myvector[0].push_back(10); 
myvector[1].push_back(20);
myvector[2].push_back(30);

The vectors myvector[0], myvector[1], and myvector[2] do not yet exist. If you want myvector to begin with 3 vectors, you can create it like so:

std::vector< std::vector<int> > myvector(3);
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

as you can see from the following link http://www.cplusplus.com/reference/vector/vector/operator[]/, operator[] is Access element tha's way you can't insert element with it. to insert objects use Assign , push_back and insert

beyrem
  • 437
  • 1
  • 3
  • 12