-
Notifications
You must be signed in to change notification settings - Fork 246
/
9.31.cpp
54 lines (44 loc) · 1.11 KB
/
9.31.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <list>
#include <forward_list>
#include <iostream>
void change(std::list<int> &li) {
for (auto iter = li.begin(); iter != li.end(); )
if (*iter % 2) {
iter = li.insert(iter, *iter);
++iter; ++iter;
//iter += 2; // Error: list doesn't support iterator arithmetic
} else
iter = li.erase(iter);
}
void change(std::forward_list<int> &fli) {
for (auto pre = fli.before_begin(), cur = fli.begin();
cur != fli.end(); ) {
if (*cur % 2) {
pre = fli.insert_after(pre, *cur);
++pre;
++cur;
} else
cur = fli.erase_after(pre);
}
}
int main() {
std::list<int> li{1, 2, 3, 4, 5, 6};
std::forward_list<int> fli{1, 2, 3, 4, 5, 6};
std::cout << "li:\n";
for (const auto & i : li)
std::cout << i << " ";
std::cout << std::endl;
change(li);
for (const auto & i : li)
std::cout << i << " ";
std::cout << std::endl;
std::cout << "fli:\n";
for (const auto & i : fli)
std::cout << i << " ";
std::cout << std::endl;
change(fli);
for (const auto & i : fli)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}