简体   繁体   中英

Segmentation fault using Vector C++

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM