c++ - Program seg faults on vector access -


i c++ newbie, learning c++ on os x yosemite.

i declaring vector in source file this.

vector <int> v(3); 

code:

#include <iostream> #include <vector>  using namespace std;  void printvector (vector <int> v) {      (int = 0; < v.size() ; i++)         cout << v[i] << endl; }  int main (int argc, char ** argv) {      vector<int> v(3);      cout << "initialise vectors..." << endl;      v[0] = 10;     v[1] = 11;     v[2] = 12;      printvector(v);      v.push_back(7);      cout << "push (7)" << endl;      printvector(v);       return 0;  } 

program worked.

i referenced webpage here , followed way declare vector this.

vector <int> v; 

compiled (using g++) fine program segfaults 11 when executed.

is website wrong?

well access elements this:

v[0] = 10; v[1] = 11; v[2] = 12; 

this requires vector have @ least 3 elements. if declare this:

vector<int> v(3);  

then has 3 elements, great. if declare this:

vector<int> v; 

then has no elements, above accesses invalid. if want create empty vector add elements it, use push_back:

v.push_back(10); v.push_back(11); v.push_back(12); 

Comments