赞
踩
9.27
- #include <iostream>
- #include <forward_list>
-
- using namespace std;
-
- int main()
- {
- forward_list<int> flist = {1, 2, 3, 4, 5, 6, 7, 8};
-
- auto prev = flist.before_begin();
- auto curr = flist.begin();
-
- while (curr != flist.end()) {
- if ((*curr)%2)
- curr = flist.erase_after(prev);
- else {
- prev = curr;
- ++curr;
- }
- }
-
- for (auto i : flist)
- cout << i << endl;
-
- return 0;
- }
9.28
- #include <iostream>
- #include <forward_list>
-
- using namespace std;
-
- void flist_insert(forward_list<string> &flist, const string s1, const string s2)
- {
- auto prev = flist.before_begin();
- auto curr = flist.begin();
- bool insert = false;
-
- while (curr != flist.end()) {
- if (*curr == s1) {
- curr = flist.insert_after(curr, s2);
- prev = curr;
- ++curr;
- insert = true;
- } else {
- prev = curr;
- ++curr;
- }
- }
-
- if (!insert) {
- flist.insert_after(prev, s2);
- }
- }
-
- int main()
- {
- forward_list<string> flist = {"s1", "s2", "s3", "s4", "s2", "s6"};
-
- flist_insert(flist, "s2", "s5");
-
- for (auto s : flist)
- cout << s << endl;
-
- flist_insert(flist, "s6", "s8");
-
- for (auto s : flist)
- cout << s << endl;
-
- /* 所有元素都相同的情况 */
- forward_list<string> flist2 = {"s1", "s1", "s1", "s1"};
- flist_insert(flist2, "s1", "s1");
-
- for (auto s : flist2)
- cout << s << endl;
-
- return 0;
- }
9.29 vec.resize(100)会向末尾新增75个元素,这些元素进行值初始化;vec.resize(10)会删除末尾的90个元素。
9.30 接受单个参数,要求该元素类型有默认构造函数。
9.31 list和forward_list的元素在内存中不连续,不支持迭代器的加减运算。修改程序如下:
- #include <iostream>
- #include <list>
- #include <forward_list>
-
- using namespace std;
-
- int main()
- {
- list<int> ilist = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
- forward_list<int> flist = {0, 1, 2, 3, 4, 5, 6 ,7, 8, 9};
-
- auto iter = ilist.begin();
- while (iter != ilist.end()) {
- if (*iter % 2) {
- iter = ilist.insert(iter, *iter);
- ++iter;
- ++iter;
- } else {
- iter = ilist.erase(iter);
- }
- }
-
- for (auto i : ilist)
- cout << i << endl;
-
- auto prev = flist.before_begin();
- auto curr = flist.begin();
- while (curr != flist.end()) {
- if (*curr % 2) {
- curr = flist.insert_after(prev, *curr);
- prev = ++curr;
- ++curr;
- } else {
- curr = flist.erase_after(prev);
-
- }
- }
-
- for (auto f : flist)
- cout << f << endl;
-
- return 0;
- }
932. 不合法,编译时会先计算第二个参数 *iter++, iter指向当前奇数的下一个元素,导致第一个参数的值错误。
9.33 向vector添加元素后,指向容器的迭代器,指针和引用都可能失效,不将insert结果赋予begin,begin会失效,继续使用可能导致程序崩溃。
9.34 该代码的目的是复制奇数元素; 代码错误:++iter应该被包括在循环体内,且应该多执行一次++iter。修改如下:
- #include <iostream>
- #include <vector>
-
- using namespace std;
-
- int main()
- {
- vector<int> vi = {1, 2, 3, 4, 5, 6, 7, 8, 9};
-
- auto iter = vi.begin();
- while (iter != vi.end()) {
- if (*iter % 2) {
- iter = vi.insert(iter, *iter);
- ++iter;
- }
- ++iter;
- }
-
- for (auto v : vi)
- cout << v << endl;
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。