Iterate through vectors

Jan 12, 2014 at 10:24am
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);

}
Jan 12, 2014 at 10:27am
line 3 is a little funny. Here you are saying:

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.
Jan 12, 2014 at 10:56am
Omg, I did not notice that. Thank you that fixed the problem! :D
Jan 12, 2014 at 5:27pm
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.
Jan 12, 2014 at 6:04pm
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' ;
}

http://coliru.stacked-crooked.com/a/c2b47f3fc5ad773b
Topic archived. No new replies allowed.