Member Avatar for ray.tan.507

I was doing some exercise from C++ Primer and one of them required us to copy a set of value from array into
a vector container. Then, we are suppose to remove all the even numbers from the vector container.
Hoever, when I tried to display them out by incrementing the iterator instead of using a normal for loop, I actually had obtained additional garbage values.

Here is my code:

#include <vector>
#include <list>
#include <iostream>

int main()
{
std::vector<int>vec;
std::list<int>li;
int ia[]={0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
for(int i(0); i<sizeof(ia);++i)
   {
      vec.push_back(ia[i]);
      li.push_back(ia[i]);
   }

auto vecIterator = vec.begin();
while(vecIterator!=vec.end())
{
   if(*vecIterator%2)
   ++vecIterator;
   else
   vec.erase(vecIterator);
}
vecIterator = vec.begin();
while(vecIterator!=vec.end())
{
   std::cout << *vecIterator <<'\n';
   ++vecIterator;
}
}

This is the array that I am supposed to copy into my vector
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };

Here is the output from my terminal
1,1,3,5,8,13,21,55,89,32767, -3489211, 32467, -34895

Helpppppp!!!!

Recommended Answers

All 4 Replies

Member Avatar for ray.tan.507

I had a feeling the problem lies with invalidate iterator after I erase the element of vector
I am just not sure how to go on and fix it

Member Avatar for ray.tan.507

Just figure out the problem after some response from other forum , something wrong with the sizeof(ia) code that returns the bytes not no of elements.

If you want to use sizeof in your for loop you need to do it like

for(int i = 0; i < sizeof(ia) / sizeof(ia[0]); i++)

If you're using C++11 (as the keyword "auto" would suggest), you can just initialize the vector in one go, without the use of an array:

vector<int> vec = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};

another trick which also works with the older standards is:

int ia[]={0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89}
vector<int> vec (ia, ia + sizeof(ia) / sizeof(ia[0]) );
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.