赞
踩
练习 9.31:第 316 页中删除偶数值元素并复制奇数值元素的程序不能用于list或forward_list。为什么?修改程序,使之也能用于这些类型。
- #include <iostream>
- #include <list>
- #include <forward_list>
-
- using std::cout;
- using std::forward_list;
- using std::list;
-
- int main()
- {
- list<int> lst = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
- auto iter = lst.begin();
- while (iter != lst.end())
- {
- if (*iter % 2)
- lst.insert(iter, *iter++);
- else
- iter = lst.erase(iter);
- }
- cout << "删除偶数元素,复制奇数元素后的lst为:";
- for (const auto &n : lst)
- cout << n << ' ';
-
- forward_list<int> flst = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
- auto prev = flst.before_begin();
- auto iterf = flst.begin();
- while (iterf != flst.end())
- {
- if (*iterf % 2)
- {
- iterf = flst.insert_after(iterf, *iterf);
- prev = iterf;
- ++iterf;
- }
- else
- {
- iterf = flst.erase_after(prev);
- }
-
- }
- cout << "\n删除偶数元素,复制奇数元素后的flst为:";
- for (const auto &n : flst)
- cout << n << ' ';
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。