C++ Primer第五版_第九章习题答案(1~10)
文章目录
- 练习9.1
- 练习9.2
- 练习9.3
- 练习9.4
- 练习9.5
- 练习9.6
- 练习9.7
- 练习9.8
- 练习9.9
- 练习9.10
练习9.1
对于下面的程序任务,vector、deque和list哪种容器最为适合?解释你的选择的理由。如果没有哪一种容器优于其他容器,也请解释理由。
- (a) 读取固定数量的单词,将它们按字典序插入到容器中。我们将在下一章中看到,关联容器更适合这个问题。
- (b) 读取未知数量的单词,总是将单词插入到末尾。删除操作在头部进行。
- © 从一个文件读取未知数量的整数。将这些数排序,然后将它们打印到标准输出。
- (a)
list
,因为需要频繁的插入操作。 - (b)
deque
,总是在头尾进行插入、删除操作。 - ©
vector
,不需要进行插入删除操作。
练习9.2
定义一个list对象,其元素类型是int的deque。
std::list<std::deque<int>> l;
练习9.3
构成迭代器范围的迭代器有何限制?
两个迭代器 begin
和 end
需满足以下条件:
- 它们指向同一个容器中的元素,或者是容器最后一个元素之后的位置。
- 我们可以通过反复递增 begin 来到达 end。换句话说,end 不在 begin 之前。
练习9.4
编写函数,接受一对指向vector的迭代器和一个int值。在两个迭代器指定的范围中查找给定的值,返回一个布尔值来指出是否找到。
bool find(vector<int>::const_iterator begin, vector<int>::const_iterator end, int i)
{
while (begin++ != end)
{
if (*begin == i)
return true;
}
return false;
}
练习9.5
重写上一题的函数,返回一个迭代器指向找到的元素。注意,程序必须处理未找到给定值的情况。
vector<int>::const_iterator find(vector<int>::const_iterator begin, vector<int>::const_iterator end, int i)
{
while (begin != end)
{
if (*begin == i)
return begin;
++begin;
}
return end;
}
练习9.6
下面的程序有何错误?你应该如何修改它?
list<int> lst1;
list<int>::iterator iter1 = lst1.begin(),
iter2 = lst1.end();
while (iter1 < iter2) /* ... */
修改成如下:
while (iter1 != iter2)
练习9.7
为了索引int 的 vector中的元素,应该使用什么类型?
vector<int>::size_type
练习9.8
为了读取string 的list 中的元素,应该使用什么类型?如果写入list,又应该使用什么类型?
list<string>::const_iterator // 读
list<string>::iterator // 写
练习9.9
begin 和 cbegin 两个函数有什么不同?
begin
返回的是普通迭代器,cbegin
返回的是常量迭代器。
练习9.10
下面4个对象分别是什么类型?
vector<int> v1;
const vector<int> v2;
auto it1 = v1.begin(), it2 = v2.begin();
auto it3 = v1.cbegin(), it4 = v2.cbegin();
这里的代码在 VS2013 下是有错误的。
- 错误 1 error C3538: 在声明符列表中,“auto”必须始终推导为同一类型 因此代码要改为
auto it1 = v1.begin();
auto it2 = v2.begin(), it3 = v1.cbegin(), it4 = v2.cbegin();
it1` 是 `vector<int>::iterator
it2`,`it3` 和 `it4` 是 `vector<int>::const_iterator