习题9-21
一样工作?!vector和list工作原理一致;
习题9-22
1、两个迭代器没有“+”运算:mid=iv.begin()+(iv.end()-iv.begin())/2 or mid =iv.begin()+iv.size();
2、iv.insert()有返回值;
习题9-23
会是c的首元素;
习题9-24
vector<int> vec;
int vec1 = vec.at(0); //out of range
int vec2 = vec[0]; //error
int vec3 = vec.front(); //error
int vec4 = *vec.begin(); //error
习题9-25
如果elem1和elem2相等,则不发生删除操作
如果elem2是尾后迭代器,则删除elem1之后的元素,返回尾后迭代器。
如果elem1和elem2都是尾后迭代器,则不发生删除操作。
习题9-26
void test926()
{
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
vector<int> ivec(begin(ia), end(ia));
list<int> ilist(begin(ia), end(ia));
vector<int>::iterator iter = ivec.begin();
while(iter != ivec.end()) {
if (!(*iter%2)) {
iter = ivec.erase(iter);
}else {
iter ++;
}
}
list<int>::iterator beg = ilist.begin();
while(beg != ilist.end()) {
if (*beg%2) {
beg = ilist.erase(beg);
}else {
beg ++;
}
}
}
习题9-27
#include<iostream>
#include<forward_list>
using namespace std;
void main()
{
forward_list<int> flst = { 0,1,2,3,4,5,6,7,8,9 };
auto prev = flst.before_begin();
auto curr = flst.begin();
while (curr != flst.end())
{
if (*curr % 2)
curr = flst.erase_after(prev);
else
{
prev = curr;
++curr;
}
}
}
习题9-28
#include<iostream>
#include<string>
#include<forward_list>
using namespace std;
void func(forward_list<string> &, const string &, const string &);
void main()
{
forward_list<string> flst{ "li","can","super","man" };
func(flst, "can", "love");
for (auto it : flst)
cout << it << " ";
cout << endl;
func(flst, "lan", "and");
for (auto it : flst)
cout << it << " ";
cout << endl;
func(flst, "and", "you");
for (auto it : flst)
cout << it << " ";
cout << endl;
}
void func(forward_list<string> &ls, const string &str1, const string &str2)
{
auto prev = ls.before_begin();
auto curr = ls.begin();
while (curr != ls.end())
{
if (*curr != str1)
{
prev = curr;
++curr;
}
else
{
curr = ls.insert_after(curr, str2);
break;
}
}
if (curr == ls.end())
curr = ls.insert_after(prev, str2);
}
习题9-29
vec.resize(100)会在末尾后增加75个元素,并进行初始化;
vec.resize(10)会从末尾开始删除90个元素;
习题9-30
我们必须提供初始值,或者如果是类类型元素,元素必须提供默认构造函数;