How would you write the following program using a forward_list
1 2 3 4 5 6 7 8 9 10 11 12
vector<int> vi = {0,1,2,3,4,5,6,7,8,9};
auto iter = vi.begin();
while (iter != vi.end()) {
if (*iter % 2) {
iter = vi.insert(iter, 42);
iter += 2;
} else
iter = vi.erase(iter);
}
return 0;
insert_after() method returns iterator to freshly inserted element. After that we need to increment it to avoid inserting same value again. This is shorthand for
1 2 3 4
while(it != vi.end()) {
it = vi.insert_after(it, *it);
++it;
}