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
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.
If you are restricted to using a C++03 compiler, use iterators.