I'm trying to iterate through a vector of structs but I keep getting this error http://i41.tinypic.com/2nvrlza.png
It works for the first one but after that it gives me the error in the picture above. I tried using ints instead and it worked just fine...
1 2 3 4 5
for (std::vector<mystruct>::iterator iter = Vect.begin(); iter != Vect.end(); ++iter)
{
Vect.insert(iter + 1, otherstruct);
}
For each object, add another one right after it. But at the same time, when you increment iter, you just get to the new object, leading to an infinite loop.
What happens if you comment out line 3? I think that's your problem.
While the actual "infinite loop" isn't advised, the problem you were running into was because insert will invalidate iterators when it requires the vector's capacity be increased.
Use the value returned by the container's insert()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <vector>
int main()
{
std::vector<int> vec { 0, 1, 2, 3, 4, 5 } ;
vec.reserve( vec.size() * 2 ) ; // optional
auto n = vec.size() ; // size before the inserts
// insert 99 at every alternate position (insert 99 n times)
for( auto iter = std::begin(vec) ; n-- ; ++iter )
iter = vec.insert( iter+1, 99 ) ; // vec.insert() returns a valid iterator
// to the element that was inserted
for( int v : vec ) std::cout << v << ' ' ;
std::cout << '\n' ;
}