On Thursday, 28 November 2013 09:59:07 UTC, Rosario1903 wrote:
> why the below goes to seg fault?
>
> #include <iostream>
> #include <vector>
> using namespace std;
>
> void f(vector<unsigned>& v)
> {v[3]=4; v[4]=9;}
>
>
> int main(void)
> {vector <unsigned> mv;
vector<unsigned> mv(6); // or more
>
> mv[0]=1; mv[1]=2;
> f(mv);
> cout<<"mv[0]="<<mv[0]<<", mv[1]="<<mv[1]<<"\n";
> cout<<"mv[3]="<<mv[3]<<", mv[4]="<<mv[4]<<" mv[5]="<<mv[5]<<"\n";
>
> return 0;
> }
When you declare a vector, with no construction arguments, it contains
exactly zero elements. Elements mv[0], mv[1], etc. do not yet exist.
This is why you get a seg-fault when trying to access them.
You can (as in my example, above) pre-allocate a number of
default-initialised elements. Or you can "manually" change the
size of the vector (using its resize() member function) or use
any of the insert()/push_back() member functions to add elements
to the vector.