forward_list

closed account (EwCjE3v7)
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;
Last edited on
why do you need forward list? It is really unsuited for such task.

Here is the code if you want:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <forward_list>


int main()
{
    std::forward_list<int> vi = {0,1,2,3,4,5,6,7,8,9};
    vi.remove_if([](int x){return (x % 2) == 0;});
    auto it = vi.begin();
    while(it != vi.end()) {
        it = ++vi.insert_after(it, *it);
    }

    for(auto x: vi)
        std::cout << x << '\n';
}
Last edited on
closed account (EwCjE3v7)
It was an exercise from my book. Can you explain line 11 please. The ++vi.insert......

I dont understand what the ++ operator does there. THank you
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;
}
closed account (EwCjE3v7)
oh alright, thank you for your help with this one and the other. :)
Topic archived. No new replies allowed.