Segmentation fault using Vector C++

2.2k views Asked by At

I am trying to separate all the values stored in a vector into two different vectors. But when i am printing value of any of the vectors it is throwing seg fault.

Below is the code sample.

std::vector<int> V,Vx,Vy;

        for (int i = 0; i < k; ++i)
        {
            cin>>x;
            V.push_back(x);
        }
        for(int i=0;i<m-1;i=i+2)
        {
            Vx.push_back(V[i]);
        }
        for(int i=1;i<m-1;i=i+2)
        {
            Vy.push_back(V[i]);
        }
        for(int i=0;i<m-1;i=i+2)
            cout<<Vx[i]<<endl;

Where am i doing wrong?? k=12, m=6

1

There are 1 answers

0
R Sahu On

The problem with

    for(int i=0;i<m-1;i=i+2)
        cout<<Vx[i]<<endl;

is that you are accessing elements of Vx using out of bounds indices.

It's good to adopt programming practices that lead to less buggy code.

If you are able to use a C++11 compiler, use the range for loop to access elements of containers.

for ( auto i : Vx )
   cout << i << endl;

If you are restricted to using a C++03 compiler, use iterators.

for ( std::vector<int>::iterator iter = Vx.begin(), iter != Vx.end(); ++iter )
   cout << *iter << endl;