简体   繁体   English

使用 Vector C++ 的分段错误

[英]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 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.是您正在使用越界索引访问Vx元素。

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.如果您能够使用 C++11 编译器,请使用范围 for 循环访问容器的元素。

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

If you are restricted to using a C++03 compiler, use iterators.如果您只能使用 C++03 编译器,请使用迭代器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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