9.1
(a) 正确,不包含sa+6这个指针所指向的数据。sa+6是数组最后一个元素的下一位。
(b) 正确
(c) 错误,数组ia的长度为7,最多指向ia+7
(d) 错误,不能逆向指示
9.2
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
using namespace std;
int main() {
// 仅指定元素个数
vector<int> arr(3);
for(auto i=0; i<arr.size(); ++i)
printf("%d\t", arr[i]);
printf("\n");
// 指定元素个数和初值
vector<int> arr1(3, 9);
for(auto i=0; i<arr1.size(); ++i)
printf("%d\t", arr1[i]);
printf("\n");
// 已知容器的副本
vector<int> arr2(arr1);
for(auto i=0; i<arr2.size(); ++i)
printf("%d\t", arr2[i]);
printf("\n");
// 已知容器副本的一部分
vector<int> arr3(arr1.begin(), arr1.begin()+1);
for(auto i=0; i<arr3.size(); ++i)
printf("%d\t", arr3[i]);
printf("\n");
// 空容器
vector<int> empty_arr;
return EXIT_SUCCESS;
}
9.3
使用复制容器对象的构造函数,相当于使用迭代器begin()和end()。
使用一对迭代器,可以复制已知容器的一部分。
9.4
list<deque<int> > data
9.5
容器对元素的要求:
1. 可以复制。
2. 可以赋值。
由于iostream对象不能复制,也不能赋值,所以没有存储iostream的容器。
9.6
class Foo {
public:
Foo(int val) {}
}
list<Foo> arr(10, 3);
9.7
错误所在:iter1 < iter2,这是由于list的迭代器不支持关系运算。应该修改为:iter1 != iter2。
9.8
vec_iter所指向的string是否为空。
9.9
两种方法:一种是利用自带的函数rbegin, rend; 另一种方法是用vector的临时变量承接。
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
class A {
};
int main() {
list<string> arr;
arr.push_back("hou");
arr.push_back("wen");
arr.push_back("ting");
for(auto iter=arr.rbegin(); iter!=arr.rend(); ++iter)
printf("%s ", iter->c_str());
printf("\n");
vector<string> tmp(arr.begin(), arr.end());
for(int i=tmp.size()-1; i>=0; --i)
printf("%s ", tmp[i].c_str());
printf("\n");
return EXIT_SUCCESS;
}
9.10
(a) 正确,const指出ivec是常量,但常量仍然具有普通迭代器
(b) 错误,list迭代器不支持算数运算,只有vector和deque两种顺序容器支持算数和关系运算。
(c) 正确,迭代器的底层实现就是指针,只不过具有相同的接口约束,也就是指向的范围被标准库限制。
(d) 错误,应该是 it != svec.end()
9.11
满足以下约束:
1. first, last必须指向同一个容器内的元素或者指向该容器最后一个元素的下一位
2. first必须在last之前,以保证first通过自增一定能到达last
9.12
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
typedef vector<int> INTVEC;
bool search(INTVEC::const_iterator first, INTVEC::const_iterator last, int val) {
while (first!=last) {
if (*first++ == val)
return true;
}
return false;
}
int main() {
INTVEC data;
for(auto i=0; i<10; ++i)
data.push_back(i);
int val;
cin >> val;
if(search(data.begin(), data.end(), val))
printf("find it %d\n", val);
else
printf("can not find %d\n", val);
return EXIT_SUCCESS;
}
9.13
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
typedef vector<int> INTVEC;
INTVEC::const_iterator search(INTVEC::const_iterator first, INTVEC::const_iterator last, int val) {
while (first!=last) {
if (*first == val)
return first;
++first;
}
return last;
}
int main() {
INTVEC data;
for(auto i=0; i<10; ++i)
data.push_back(i);
int val;
cin >> val;
if(data.end() != search(data.begin(), data.end(), val))
printf("find it %d\n", val);
else
printf("can not find %d\n", val);
return EXIT_SUCCESS;
}
9.14
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
typedef vector<int> INTVEC;
INTVEC::const_iterator search(INTVEC::const_iterator first, INTVEC::const_iterator last, int val) {
while (first!=last) {
if (*first == val)
return first;
++first;
}
return last;
}
int main() {
string tmp;
vector<string> data;
while (getline(cin, tmp)) {
if (tmp == "quit")
break;
data.push_back(tmp);
}
for(auto iter=data.begin(); iter!=data.end(); ++iter)
printf("%s ", iter->c_str());
printf("\n");
return EXIT_SUCCESS;
}
9.15
参见上题,由于迭代器具有一致的接口,上述代码只需要用list替换vector即可。
9.16
如下所示,可以使用两种类型的iter,区别在于是否const
vector<int>::size_type
9.17
vector<string>::const_iterator
9.18
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
int main() {
list<int> ilist;
for(int i=0; i<10; ++i)
ilist.push_back(i);
deque<int> arr, arr1;
for(auto iter=ilist.begin(); iter!=ilist.end(); ++iter)
if(*iter%2)
arr.push_back(*iter);
else
arr1.push_back(*iter);
printf("ji shu: ");
deque<int>::const_iterator iter=arr.begin();
while (iter!=arr.end())
printf("%d ", *iter++);
printf("\n");
return EXIT_SUCCESS;
}
9.19
iter没有初始化
iter == some_val, 没有接引用
insert返回插入元素的iter,没有更新iter
应该修改为:
vector<int>::iterator iter=iv.begin();
while(iter != (iv.begin()+iv.size()/2))
if(*iter++ == some_val) {
iter = iv.insert(iter, 2*some_val);
++iter;
}
这里发现书中有一处错误:
while(first != v.end()) {
first = v.insert(first, 42); // 返回插入的元素的迭代器,也就是原来的元素A的前一个
++first; // 只移动一位,那么指向的是原来的元素A,这里应该是 first +=2;
}
9.20
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
bool isEq(list<int>& lhs, vector<int>& rhs) {
if(lhs.size() != rhs.size())
return false;
else {
auto i=lhs.begin();
auto j=rhs.begin();
for(; i!=lhs.end(), j!=rhs.end(); ++i, ++j)
if(*i != *j)
return false;
}
return true;
}
int main() {
list<int> ilist;
for(int i=0; i<10; ++i)
ilist.push_back(i);
vector<int> ivec(ilist.begin(), ilist.end());
if(isEq(ilist, ivec))
printf("same\n");
else
printf("different\n");
return EXIT_SUCCESS;
}
9.21
约束是:
1. c1,c2的类型相同,而且元素的类型也相同
2. 两个容器的元素类型,支持小于操作符
9.22
实现增加75个元素,每个元素采用值初始化策略。
vec.resize(10),保留前10个元素,其余的删除。
9.23
只带一个参数的resize,采用值初始化策略,对于内置类型,都满足要求。对应类类型,必须具有默认构造函数。
9.24
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
int main() {
list<int> ilist;
for(int i=0; i<10; ++i)
ilist.push_back(i);
vector<int> ivec(ilist.begin(), ilist.end());
printf("%d %d\n", ivec.size(), ivec.max_size());
ivec.resize(3);
printf("%d %d\n", ivec.size(), ivec.max_size());
ivec.resize(10, 100);
printf("%d %d\n", ivec.size(), ivec.max_size());
for(auto i=0; i<ivec.size(); ++i)
printf("%d ", ivec[i]);
printf("\n");
printf("[] %d\n", ivec[101]); // 运行时错误,通常会crash
cout << endl;
printf("at() %d\n", ivec.at(101)); // 抛出异常,一定会crash,这是个巨大的优点
vector<int>::reference k = ivec.back();
cout << k << endl;
vector<int>::iterator iter = ivec.end();
cout << *(--iter) << endl;
vector<int>::const_reference kk = ivec.front();
cout << kk << endl;
vector<int>::const_iterator it = ivec.begin();
cout << *it << endl;
cout << ivec[0] << endl;
ivec.clear();
vector<int>::const_reference kkk = ivec.front();
cout << kkk << endl;
vector<int>::const_iterator itt = ivec.begin();
cout << *itt << endl;
cout << ivec[0] << endl;
cout << ivec.at(0) << endl;
return EXIT_SUCCESS;
}
9.25
顺序容器中删除一部分元素的程序如下:
list<int>::iterator elem1, elem2;
elem1 = find(ilist.begin(), ilist.end(), val1);
elem2 = find(elem1, ilist.end(), val2);
ilist.erase(elem1, elem2);
如果val1==val2,elem1==elem2,则不删除任何元素。
如果val1没找到,elem1==ilist.end(),则elem2也是ilist.end()
如果val2没找到,那么elem2就是ilist.end(),所以就删除了elem1之后的所有元素。
如果val1和val2都没找到,那么elem1==elem2=ilist.end(),则程序不删除任何元素。
9.26
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
void print(const list<int> &ilist);
void print(const vector<int> &ivec);
int main() {
int ia[] = {0,1,1,2,3,5,8,13,21,55,89};
int sz = sizeof(ia) / sizeof(ia[0]);
vector<int> ivec(ia, ia+sz);
list<int> ilist(ia, ia+sz);
for(auto iter=ivec.begin(); iter!=ivec.end();)
if(*iter%2)
++iter;
else
iter = ivec.erase(iter);
print(ivec);
for(auto iter=ilist.begin(); iter!=ilist.end();)
if(*iter%2==0)
++iter;
else
iter = ilist.erase(iter);
print(ilist);
return EXIT_SUCCESS;
}
void print(const list<int> &ilist) {
if(ilist.empty()) {
printf("list empty\n");
return;
}
printf("list: ");
for(auto iter=ilist.begin(); iter!=ilist.end(); ++iter)
printf("%d ", *iter);
printf("\n");
}
void print(const vector<int> &ivec) {
if(ivec.empty()) {
printf("vector empty\n");
return;
}
printf("vector: ");
for(auto iter=ivec.begin(); iter!=ivec.end(); ++iter)
printf("%d ", *iter);
printf("\n");
}
9.27
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
void print(const list<int> &ilist);
void print(const vector<int> &ivec);
int main() {
list<string> slist;
string tmp;
ifstream fin("Makefile");
while (fin >> tmp)
slist.push_back(tmp);
fin.close();
string target("because");
list<string>::iterator iter = find(slist.begin(), slist.end(), target);
if (iter != slist.end()) {
iter = slist.erase(iter);
printf("%s\n", iter->c_str());
} else {
printf("can not find\n");
for(auto it=slist.begin(); it!=slist.end(); ++it)
printf("%s\n", it->c_str());
}
return EXIT_SUCCESS;
}
9.28
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
void print(const list<int> &ilist);
void print(const vector<int> &ivec);
int main() {
char data[][10] = {"C++", "perl", "python", "java", "go"};
list<char*> pclist(data, data+5);
vector<string> arr;
arr.assign(pclist.begin(), pclist.end());
for(auto i=0; i<arr.size(); ++i)
cout << arr[i] << endl;
return EXIT_SUCCESS;
}
void print(const list<int> &ilist) {
if(ilist.empty()) {
printf("list empty\n");
return;
}
printf("list: ");
for(auto iter=ilist.begin(); iter!=ilist.end(); ++iter)
printf("%d ", *iter);
printf("\n");
}
void print(const vector<int> &ivec) {
if(ivec.empty()) {
printf("vector empty\n");
return;
}
printf("vector: ");
for(auto iter=ivec.begin(); iter!=ivec.end(); ++iter)
printf("%d ", *iter);
printf("\n");
}
9.29
vector的长度,size(),是当前容器包含的元素个数。容量是该容器再次分配内存之前,可以容纳的元素总数。因为vector采用连续的地址来存放元素,如果不预留一部分空间,则每增加一个元素都需要重新分配内存,复制旧的元素,添加新的元素,删除旧的元素。这样的性能代价太差。
对于不连续的容器,比如list,没有上述内存分配的考虑。新添加元素只需要链接到list即可。
9.30
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
void print(const list<int> &ilist);
void print(const vector<int> &ivec);
int main() {
char data[][10] = {"C++", "perl", "python", "java", "go"};
list<char*> pclist(data, data+5);
vector<string> arr;
arr.assign(pclist.begin(), pclist.end());
printf("capacity=%d, size=%d, %s\n", arr.capacity(), arr.size(),
arr.capacity()==arr.size()?"vector is full, if push new elem, need alloc new memory":"has reserved memory");
arr.push_back("hehe");
printf("\npush a new elem, capacity=%d, size=%d\n", arr.capacity(), arr.size());
while (arr.size()!=arr.capacity())
arr.push_back("che");
printf("\nmake full vector, capacity=%d, size=%d\n", arr.capacity(), arr.size());
arr.reserve(100);
printf("\nreserved 100 elem space, capacity=%d, size=%d\n", arr.capacity(), arr.size());
return EXIT_SUCCESS;
}
void print(const list<int> &ilist) {
if(ilist.empty()) {
printf("list empty\n");
return;
}
printf("list: ");
for(auto iter=ilist.begin(); iter!=ilist.end(); ++iter)
printf("%d ", *iter);
printf("\n");
}
void print(const vector<int> &ivec) {
if(ivec.empty()) {
printf("vector empty\n");
return;
}
printf("vector: ");
for(auto iter=ivec.begin(); iter!=ivec.end(); ++iter)
printf("%d ", *iter);
printf("\n");
}
9.31
不可以。
空容器,size()==capacity()==0.
大部分时间,size()!=capacity(),capacity总是要多一些。为了将来插入新的元素,不需要重新分配内存空间。
9.32
功能:先预分配内存空间,再输入数据
1024
如果读入512,100,都不会重新分配内存
如果读入1048,重新分配内存,通常capacity翻倍。
9.33
(a) 适合vector,生成英文句子,需要随机访问单词。
(b) 适合list,要求顺序插入,相当的可能在非末尾位置插入元素。
(d) 适合list,一端插入,另一端删除,典型的队列操作。
(d) 适合vector,没有要求在容器中间插入元素,一律选择vector。
9.34
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
const char *cp = "zhaosp";
string s(cp);
for(auto iter=s.begin(); iter!=s.end(); ++iter)
*iter = toupper(*iter);
cout << s << endl;
return EXIT_SUCCESS;
}
9.35
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
const char *cp = "zhaoABCsp";
string s(cp);
for(auto iter=s.begin(); iter!=s.end(); ) {
if(isupper(*iter))
iter = s.erase(iter);
else
++iter;
}
cout << s << endl;
return EXIT_SUCCESS;
}
9.36
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
vector<char> data(10, 'z');
string s(data.begin(), data.end());
cout << s << endl;
return EXIT_SUCCESS;
}
9.37
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
string s;
s.reserve(100);
char ch;
ifstream fin("Makefile");
while (fin >> ch) {
if (s.size() >= 100)
break;
s.push_back(ch);
}
fin.close();
cout << s << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
return EXIT_SUCCESS;
}
9.38
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
string numerics("0123456789");
string name("ab2c3d7R4E6");
string alphabet;
for(auto i=0; i<26; ++i) {
alphabet.push_back(char('a'+i));
alphabet.push_back(char('A'+i));
}
string::size_type pos = 0;
printf("search numberics\n");
while ((pos = name.find_first_of(numerics, pos)) != string::npos) {
printf("pos:%d, val:%c\n", pos, name[pos]);
++pos;
}
pos = 0;
printf("\nsearch alphabet\n");
while ((pos = name.find_first_of(alphabet, pos)) != string::npos) {
printf("pos:%d, val:%c\n", pos, name[pos]);
++pos;
}
pos = 0;
printf("\nsearch numberics\n");
while ((pos = name.find_first_not_of(alphabet, pos)) != string::npos) {
printf("pos:%d, val:%c\n", pos, name[pos]);
++pos;
}
pos = 0;
printf("\nsearch alphabet\n");
while ((pos = name.find_first_not_of(numerics, pos)) != string::npos) {
printf("pos:%d, val:%c\n", pos, name[pos]);
++pos;
}
return EXIT_SUCCESS;
}
9.39
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
string line1 = "We were her pride of 10 she named us:";
string line2 = "Benjamin, Phoenix, the Prodigal";
string line3 = "and perspicacious pacific Suzanne";
string sentence = line1 + ' ' + line2 + ' ' + line3;
stringstream sin(sentence);
string tmp;
int cnt = 0;
int longest(0), shortest(sentence.size());
int i, j;
while (sin >> tmp) {
if (tmp.size() > longest)
longest = tmp.size();
if(tmp.size() < shortest)
shortest = tmp.size();
++cnt;
}
printf("words num:%d\n", cnt);
sin.clear();
stringstream sin2(sentence);
while (sin2 >> tmp) {
if(tmp.size() == longest)
printf("longest word:%s\n", tmp.c_str());
if(tmp.size() == shortest)
printf("shortest word:%s\n", tmp.c_str());
}
return EXIT_SUCCESS;
}
9.40
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
#include <cstring>
using namespace std;
int main() {
string q1("When lilacs last in the dooryard bllom'd");
string q2("The child is father of the man");
string target;
target.assign(q2, 0, q2.find("father")-1);
target.append(q1, q1.find(" in the dooryard"), strlen(" in the dooryard"));
cout << target << endl;
return EXIT_SUCCESS;
}
9.41