《C++ Primer》第10章 泛型算法
导读本章介绍了标准库算法,包括:
●基础的只读算法、写容器元素的算法。
●利用lambda、bind等技术手段定制操作。
●更深入的迭代器知识,如插入器、IO流迭代器、反向迭代器。
●泛型算法对迭代器的分类和算法命名规范,以及特定容器算法。
本章练习的最重要目的是让读者深入理解“泛型”思想,体会标准库是如何通过算法和数据结构的分离来实现泛型的,以及如何通过迭代器在分离的算法和数据结构间架起桥梁,达到算法“不知”数据结构,但又能操纵数据元素的效果。具体内容包括基础算法使用的练习、lambda和定制操作的练习、插入器/IO流迭代器/反向迭代器的练习等。
10.1节 概述 习题答案
练习10.1:头文件algorithm中定义了一个名为count的函数,它类似find,接受一对迭代器和一个值作为参数。count返回给定值在序列中出现的次数。编写程序,读取int序列存入vector中,打印有多少个元素的值等于给定值。
【出题思路】
本题练习泛型算法的简单使用。
【解答】
泛型算法的使用其实很简单,记住关键一点:泛型算法不会直接调用容器的操作,而是通过迭代器来访问、修改、移动元素。对于本题,将vector的begin和end传递给count,并将要查找的值作为第三个参数传递给它即可。
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char *argv[]) {
ifstream in(argv[1]);
if(!in)
{
cout << "打开输入文件失败!" << endl;
exit(1);
}
vector<int> vi;
int val;
while(in >> val)
{
vi.push_back(val);
}
cout << "请输入要搜索的整数:" << endl;
cin >> val;
cout << "序列中包含 " << count(vi.begin(), vi.end(), val) << " 个" << val << endl;
return 0;
}
data10_01.txt里的数据为:
25 36 98 74 24 588 25 694 24 258 636 5 25 478 24 58 24 15 47 24
设置命令行参数
运行结果:
练习10.2:重做上一题,但读取string序列存入list中。
【出题思路】
理解“泛型”的优点。
【解答】
可以看到,与上一题对比,程序的变化只在不同类型变量的声明上,而算法的使用部分几乎没有任何差异。
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <list>
#include <string>
using namespace std;
int main(int argc, const char *argv[])
{
ifstream in(argv[1]);
if(!in)
{
cout << "打开输入文件失败!" << endl;
exit(1);
}
list<string> ls;
string word;
while(in >> word)
{
ls.push_back(word);
}
cout << "请输入要搜索的字符串:" << endl;
cin >> word;
cout << "序列中包含 " << count(ls.begin(), ls.end(), word) << " 个 " << word << endl;
return 0;
}
data10_02.txt里的数据为:
While deleting the derived data eventually worked for me, it didn't help until I rebooted the iPad and OS/X, emptied the trash after using the Finder to delete the derived data, and removed a BLE peripheral connected via a USB port. I don't know which of the steps was required--XCode later compiled with the BLE peripheral attached--but once all of those steps were added to deleting the derived data, the project compiled fine.
设置命令行参数,运行结果: