loop problem

May 22, 2014 at 5:58pm
closed account (EwCjE3v7)
Why does the following loop never exit?

1
2
3
4
5
6
7
8
9
vector<int> vi = {1,2,3,4,5,6,7,8,9};
	auto iter = vi.begin();

	while (iter != vi.end()) {
		if (*iter % 2) {
			iter = vi.insert(iter, *iter);
		}
		++iter;
	}
May 22, 2014 at 6:08pm
Because you're forever adding entries to the vector.

When you get to any odd number, you add it to the end of the vector, thereby increasing the size of the vector.

edit: Struck out "the end of".
Last edited on May 22, 2014 at 6:27pm
May 22, 2014 at 6:15pm
Note that insert() returns iterator to the returned element.
What happens on vector {2, 4, 5, 6}
1) Iteration goes until first odd number:
1
2
2, 4, 5, 6
//    ↑iterator 

2) then you insert this value again:
1
2
2, 4, 5, 5, 6
//    ↑iterator to the fresly inserted value 

3) then you increment iterator
1
2
2, 4, 5, 5, 6
//       ↑iterator 

4) Value is odd again, goto (2)
May 22, 2014 at 6:31pm
closed account (EwCjE3v7)
Oh thank you all, so I would need to do iter += 2; to fix it. Thank you guys
Topic archived. No new replies allowed.