change list while iterating trough it

hello everybody
i'm trying to make changes to a std::list of ints while iterating trough it.i simply check each element, and if it is equal to 10, i delete it and add two new elements, with the value of 5 and 6.
while debugging, it seems to work fine until it reaches the last element with the value of 10, when it freezes (no error message, it just freezes, probably stuck in some infinite loop).
any help is apreciated. thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <list>
#include <iterator>

int main(){
    std::list<int> my_list (4, 10);

    std::list<int>::iterator i = my_list.begin();
    while (i != my_list.end()){
        if (*i == 10){
            std::cout << *i;
            my_list.push_back(5);
            my_list.push_back(6);
            my_list.erase(i++);
        }
    }
    std::cout << std::endl;
    for (auto &n : my_list){
        std::cout << n << ",";
    }
    return 0;
}
What if *i is not 10?

1
2
3
4
5
while (i != my_list.end()){
	if (*i == 10) {
		...
	}
}

Last edited on
geez, i can't believe it.

just added
else i++
after line 15.
thanks for the help :)
Last edited on
Topic archived. No new replies allowed.